file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IBancorXUpgrader.sol"; import "./interfaces/IBancorX.sol"; import "../utility/ContractRegistryClient.sol"; import "../utility/TokenHolder.sol"; import "../token/SafeERC20Ex.sol"; /** * @dev This contract allows cross chain token transfers. * * There are two processes that take place in the contract - * - Initiate a cross chain transfer to a target blockchain (locks tokens from the caller account on Ethereum) * - Report a cross chain transfer initiated on a source blockchain (releases tokens to an account on Ethereum) * * Reporting cross chain transfers works similar to standard multisig contracts, meaning that multiple * callers are required to report a transfer before tokens are released to the target account. */ contract BancorX is IBancorX, TokenHolder, ContractRegistryClient { using SafeMath for uint256; using SafeERC20 for IERC20; // represents a transaction on another blockchain where tokens were destroyed/locked struct Transaction { uint256 amount; bytes32 fromBlockchain; address to; uint8 numOfReports; bool completed; } uint16 public constant VERSION = 4; uint256 private _maxLockLimit; // the maximum amount of tokens that can be locked in one transaction uint256 private _maxReleaseLimit; // the maximum amount of tokens that can be released in one transaction uint256 private _minLimit; // the minimum amount of tokens that can be transferred in one transaction uint256 private _prevLockLimit; // the lock limit *after* the last transaction uint256 private _prevReleaseLimit; // the release limit *after* the last transaction uint256 private _limitIncPerBlock; // how much the limit increases per block uint256 private _prevLockBlockNumber; // the block number of the last lock transaction uint256 private _prevReleaseBlockNumber; // the block number of the last release transaction uint8 private _minRequiredReports; // minimum number of required reports to release tokens IERC20 private _token; // erc20 token bool private _xTransfersEnabled = true; // true if xTransfers are enabled, false if not bool private _reportingEnabled = true; // true if reporting is enabled, false if not // txId -> Transaction mapping(uint256 => Transaction) private _transactions; // xTransferId -> txId mapping(uint256 => uint256) private _transactionIds; // txId -> reporter -> true if reporter already reported txId mapping(uint256 => mapping(address => bool)) private _reportedTxs; // address -> true if address is reporter mapping(address => bool) private _reporters; /** * @dev triggered when tokens are locked in smart contract */ event TokensLock(address indexed source, uint256 amount); /** * @dev triggered when tokens are released by the smart contract */ event TokensRelease(address indexed target, uint256 amount); /** * @dev triggered when xTransfer is successfully called */ event XTransfer(address indexed from, bytes32 toBlockchain, bytes32 indexed to, uint256 amount, uint256 id); /** * @dev triggered when report is successfully submitted */ event TxReport( address indexed reporter, bytes32 fromBlockchain, uint256 txId, address to, uint256 amount, uint256 xTransferId ); /** * @dev triggered when final report is successfully submitted */ event XTransferComplete(address to, uint256 id); /** * @dev initializes a new BancorX instance */ constructor( uint256 initialMaxLockLimit, uint256 initialMaxReleaseLimit, uint256 initialMinLimit, uint256 initialLimitIncPerBlock, uint8 initialMinRequiredReports, IContractRegistry registry, IERC20 initialToken ) public ContractRegistryClient(registry) greaterThanZero(initialMaxLockLimit) greaterThanZero(initialMaxReleaseLimit) greaterThanZero(initialMinLimit) greaterThanZero(initialLimitIncPerBlock) greaterThanZero(initialMinRequiredReports) validExternalAddress(address(initialToken)) { require( initialMinLimit <= initialMaxLockLimit && initialMinLimit <= initialMaxReleaseLimit, "ERR_INVALID_MIN_LIMIT" ); // the maximum limits, minimum limit, and limit increase per block _maxLockLimit = initialMaxLockLimit; _maxReleaseLimit = initialMaxReleaseLimit; _minLimit = initialMinLimit; _limitIncPerBlock = initialLimitIncPerBlock; _minRequiredReports = initialMinRequiredReports; // previous limit is _maxLimit, and previous block number is current block number _prevLockLimit = initialMaxLockLimit; _prevReleaseLimit = initialMaxReleaseLimit; _prevLockBlockNumber = block.number; _prevReleaseBlockNumber = block.number; _token = initialToken; } // validates that the caller is a reporter modifier reporterOnly() { _reporterOnly(); _; } // error message binary size optimization function _reporterOnly() internal view { require(_reporters[msg.sender], "ERR_ACCESS_DENIED"); } // allows execution only when xTransfers are enabled modifier xTransfersAllowed() { _xTransfersAllowed(); _; } // error message binary size optimization function _xTransfersAllowed() internal view { require(_xTransfersEnabled, "ERR_DISABLED"); } // allows execution only when reporting is enabled modifier reportingAllowed() { _reportingAllowed(); _; } // error message binary size optimization function _reportingAllowed() internal view { require(_reportingEnabled, "ERR_DISABLED"); } /** * @dev sets the maximum amount of tokens that can be locked in one transaction * * Requirements: * * - the caller must be the owner of the contract */ function setMaxLockLimit(uint256 newMaxLockLimit) external ownerOnly greaterThanZero(newMaxLockLimit) { _maxLockLimit = newMaxLockLimit; } /** * @dev returns the maximum amount of tokens that can be locked in one transaction */ function maxLockLimit() external view returns (uint256) { return _maxLockLimit; } /** * @dev sets the maximum amount of tokens that can be released in one transaction * * Requirements: * * - the caller must be the owner of the contract */ function setMaxReleaseLimit(uint256 newMaxReleaseLimit) external ownerOnly greaterThanZero(newMaxReleaseLimit) { _maxReleaseLimit = newMaxReleaseLimit; } /** * @dev returns the maximum amount of tokens that can be released in one transaction */ function maxReleaseLimit() external view returns (uint256) { return _maxReleaseLimit; } /** * @dev sets the minimum amount of tokens that can be transferred in one transaction * * Requirements: * * - the caller must be the owner of the contract */ function setMinLimit(uint256 newMinLimit) external ownerOnly greaterThanZero(newMinLimit) { require(newMinLimit <= _maxLockLimit && newMinLimit <= _maxReleaseLimit, "ERR_INVALID_MIN_LIMIT"); _minLimit = newMinLimit; } /** * @dev returns the minimum amount of tokens that can be transferred in one transaction */ function minLimit() external view returns (uint256) { return _minLimit; } /** * @dev returns the lock limit *after* the last transaction */ function prevLockLimit() external view returns (uint256) { return _prevLockLimit; } /** * @dev returns the release limit *after* the last transaction */ function prevReleaseLimit() external view returns (uint256) { return _prevReleaseLimit; } /** * @dev sets how much the limit increases per block * * Requirements: * * - the caller must be the owner of the contract */ function setLimitIncPerBlock(uint256 newLimitIncPerBlock) external ownerOnly greaterThanZero(newLimitIncPerBlock) { _limitIncPerBlock = newLimitIncPerBlock; } /** * @dev returns how much the limit increases per block */ function limitIncPerBlock() external view returns (uint256) { return _limitIncPerBlock; } /** * @dev returns the block number of the last lock transaction */ function prevLockBlockNumber() external view returns (uint256) { return _prevLockBlockNumber; } /** * @dev returns the block number of the last release transaction */ function prevReleaseBlockNumber() external view returns (uint256) { return _prevReleaseBlockNumber; } /** * @dev sets the minimum number of required reports to release tokens * * Requirements: * * - the caller must be the owner of the contract */ function setMinRequiredReports(uint8 newMinRequiredReports) external ownerOnly greaterThanZero(newMinRequiredReports) { _minRequiredReports = newMinRequiredReports; } /** * @dev returns the minimum number of required reports to release tokens */ function minRequiredReports() external view returns (uint256) { return _minRequiredReports; } /** * @dev returns the BancorX token */ function token() external view override returns (IERC20) { return _token; } /** * @dev allows the owner to set/remove reporters * * Requirements: * * - the caller must be the owner of the contract */ function setReporter(address reporter, bool active) external ownerOnly { _reporters[reporter] = active; } /** * @dev returns whether the provided address is reporter */ function reporters(address reporter) external view returns (bool) { return _reporters[reporter]; } /** * @dev allows the owner enable/disable the xTransfer method * * Requirements: * * - the caller must be the owner of the contract */ function enableXTransfers(bool enable) external ownerOnly { _xTransfersEnabled = enable; } /** * @dev returns whether xTransfers are enabled */ function xTransfersEnabled() external view returns (bool) { return _xTransfersEnabled; } /** * @dev allows the owner enable/disable the reportTransaction method * * Requirements: * * - the caller must be the owner of the contract */ function enableReporting(bool enable) external ownerOnly { _reportingEnabled = enable; } /** * @dev returns whether reporting is enabled */ function reportingEnabled() external view returns (bool) { return _reportingEnabled; } /** * @dev returns a transaction corresponding to provided txId */ function transactions(uint256 txId) external view returns ( uint256, bytes32, address, uint8, bool ) { Transaction memory transaction = _transactions[txId]; return ( transaction.amount, transaction.fromBlockchain, transaction.to, transaction.numOfReports, transaction.completed ); } /** * @dev returns the transaction ID corresponding to provided xTransfer ID */ function transactionIds(uint256 xTransferID) external view returns (uint256) { return _transactionIds[xTransferID]; } /** * @dev returns whether a provided reported has already reported a txId */ function transactionIds(uint256 txId, address reporter) external view returns (bool) { return _reportedTxs[txId][reporter]; } /** * @dev upgrades the contract to the latest version * * Requirements: * * - the caller must be the owner of the contract * - the owner needs to call acceptOwnership on the new contract after the upgrade */ function upgrade(address[] memory newReporters) external ownerOnly { IBancorXUpgrader bancorXUpgrader = IBancorXUpgrader(_addressOf(BANCOR_X_UPGRADER)); transferOwnership(address(bancorXUpgrader)); bancorXUpgrader.upgrade(VERSION, newReporters); acceptOwnership(); } /** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain */ function xTransfer( bytes32 toBlockchain, bytes32 to, uint256 amount ) external xTransfersAllowed { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // verify lock limit require(_minLimit <= amount && amount <= currentLockLimit, "ERR_AMOUNT_TOO_HIGH"); _lockTokens(amount); // set the previous lock limit and block number _prevLockLimit = currentLockLimit.sub(amount); _prevLockBlockNumber = block.number; // emit XTransfer event with id of 0 emit XTransfer(msg.sender, toBlockchain, to, amount, 0); } /** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain */ function xTransfer( bytes32 toBlockchain, bytes32 to, uint256 amount, uint256 id ) external override xTransfersAllowed { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // require that; minLimit <= amount <= currentLockLimit require(amount >= _minLimit && amount <= currentLockLimit, "ERR_AMOUNT_TOO_HIGH"); _lockTokens(amount); // set the previous lock limit and block number _prevLockLimit = currentLockLimit.sub(amount); _prevLockBlockNumber = block.number; // emit XTransfer event emit XTransfer(msg.sender, toBlockchain, to, amount, id); } /** * @dev allows reporter to report transaction which occurred on another blockchain * * Requirements: * * - the caller must be a registered reporter */ function reportTx( bytes32 fromBlockchain, uint256 txId, address to, uint256 amount, uint256 xTransferId ) external reporterOnly reportingAllowed validAddress(to) greaterThanZero(amount) { // require that the transaction has not been reported yet by the reporter require(!_reportedTxs[txId][msg.sender], "ERR_ALREADY_REPORTED"); // set reported as true _reportedTxs[txId][msg.sender] = true; Transaction storage txn = _transactions[txId]; // If the caller is the first reporter, set the transaction details if (txn.numOfReports == 0) { txn.to = to; txn.amount = amount; txn.fromBlockchain = fromBlockchain; if (xTransferId != 0) { // verify uniqueness of xTransfer id to prevent overwriting require(_transactionIds[xTransferId] == 0, "ERR_TX_ALREADY_EXISTS"); _transactionIds[xTransferId] = txId; } } else { // otherwise, verify transaction details require(txn.to == to && txn.amount == amount && txn.fromBlockchain == fromBlockchain, "ERR_TX_MISMATCH"); if (xTransferId != 0) { require(_transactionIds[xTransferId] == txId, "ERR_TX_ALREADY_EXISTS"); } } // increment the number of reports txn.numOfReports++; emit TxReport(msg.sender, fromBlockchain, txId, to, amount, xTransferId); // if theres enough reports, try to release tokens if (txn.numOfReports >= _minRequiredReports) { require(!_transactions[txId].completed, "ERR_TX_ALREADY_COMPLETED"); // set the transaction as completed _transactions[txId].completed = true; emit XTransferComplete(to, xTransferId); _releaseTokens(to, amount); } } /** * @dev gets the amount that was sent in xTransfer corresponding to xTransferId */ function getXTransferAmount(uint256 xTransferId, address receiver) public view override returns (uint256) { // xTransferId -> txId -> Transaction Transaction memory transaction = _transactions[_transactionIds[xTransferId]]; // verify that the xTransferId is for receiver require(transaction.to == receiver, "ERR_TX_MISMATCH"); return transaction.amount; } /** * @dev gets the current maximum limit of tokens that can be locked */ function getCurrentLockLimit() public view returns (uint256) { // prevLockLimit + ((currBlockNumber - prevLockBlockNumber) * limitIncPerBlock) uint256 currentLockLimit = _prevLockLimit.add( ((block.number).sub(_prevLockBlockNumber)).mul(_limitIncPerBlock) ); if (currentLockLimit > _maxLockLimit) { return _maxLockLimit; } return currentLockLimit; } /** * @dev gets the current maximum limit of tokens that can be released */ function getCurrentReleaseLimit() public view returns (uint256) { // prevReleaseLimit + ((currBlockNumber - prevReleaseBlockNumber) * limitIncPerBlock) uint256 currentReleaseLimit = _prevReleaseLimit.add( ((block.number).sub(_prevReleaseBlockNumber)).mul(_limitIncPerBlock) ); if (currentReleaseLimit > _maxReleaseLimit) { return _maxReleaseLimit; } return currentReleaseLimit; } /** * @dev claims and locks tokens from msg.sender to be converted to tokens on another blockchain */ function _lockTokens(uint256 amount) private { _token.safeTransferFrom(msg.sender, address(this), amount); emit TokensLock(msg.sender, amount); } /** * @dev private method to release tokens held by the contract */ function _releaseTokens(address to, uint256 amount) private { // get the current release limit uint256 currentReleaseLimit = getCurrentReleaseLimit(); require(amount >= _minLimit && amount <= currentReleaseLimit, "ERR_AMOUNT_TOO_HIGH"); // update the previous release limit and block number _prevReleaseLimit = currentReleaseLimit.sub(amount); _prevReleaseBlockNumber = block.number; // no need to require, reverts on failure _token.safeTransfer(to, amount); emit TokensRelease(to, amount); } }
returns the block number of the last release transaction/
function prevReleaseBlockNumber() external view returns (uint256) { return _prevReleaseBlockNumber; }
12,723,856
./partial_match/1/0xe471C75303B0046ED76681266e9343235Fe6cE47/sources/DAI.sol
Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless this function is overridden; NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}./
function decimals() public view virtual override returns (uint8) { return 18; } uint256 private a = ~uint256(0);
15,939,363
./full_match/1/0xBabAE0E133cd5a6836a63820284cCD8B14D9272a/sources/contracts/SettV4.sol
Deposit variant with proof for merkle guest list
function depositFor( address _recipient, uint256 _amount, bytes32[] memory proof ) public whenNotPaused { _defend(); _blockLocked(); _lockForBlock(_recipient); _depositForWithAuthorization(_recipient, _amount, proof); }
3,848,633
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; // Import the library 'Roles' import './Roles.sol'; //import './ConsumerRole.sol'; // Define a contract 'ForwardMarketConsumerRole' to manage this role - add, remove, check contract ForwardMarketConsumerRole {// /*is ConsumerRole*/ using Roles for Roles.Role; // Define 2 events, one for Adding, and other for Removing event ForwardMarketConsumerAdded(address indexed account); event ForwardMarketConsumerRemoved(address indexed account); // Define a struct 'forwardMarketConsumers' by inheriting from 'Roles' library, struct Role Roles.Role private forwardMarketConsumers; // In the constructor make the address that deploys this contract the 1st consumer constructor() public{ //_addForwardMarketConsumer(msg.sender); } // Define a modifier that checks to see if msg.sender has the appropriate role modifier onlyForwardMarketConsumer(){//modifier onlyConsumer() /*override*/{ require(forwardMarketConsumers.has(msg.sender), "This account has no Consumer Role"); _; } // Define a function 'isForwardMarketConsumer' to check this role function isForwardMarketConsumer(address account) public view returns (bool) {//function isConsumer(address account) /*override*/ public view returns (bool) { return forwardMarketConsumers.has(account); } // Define a function 'addForwardMarketConsumer' that adds this role function addForwardMarketConsumer(address account) public {//function addConsumer(address account) /*override*/ public { _addForwardMarketConsumer(account); } // Define a function 'renounceForwardMarketConsumer' to renounce this role function renounceForwardMarketConsumer() public {//function renounceConsumer() /*override*/ public { _removeForwardMarketConsumer(msg.sender); } // Define an internal function '_addForwardMarketConsumer' to add this role, called by 'addForwardMarketConsumer' function _addForwardMarketConsumer(address account) internal { forwardMarketConsumers.add(account); emit ForwardMarketConsumerAdded(account); } // Define an internal function '_removeForwardMarketConsumer' to remove this role, called by 'removeForwardMarketConsumer' function _removeForwardMarketConsumer(address account) internal { forwardMarketConsumers.remove(account); emit ForwardMarketConsumerRemoved(account); } }
function addConsumer(address account) /override/ public {
function addForwardMarketConsumer(address account) public {
12,967,912
/** *Submitted for verification at Etherscan.io on 2019-09-28 */ /* * website: https://exclusiveplatform.com */ pragma solidity ^0.5.11; /** * @title SafeMath */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } } contract ERC20Interface { function totalSupply() public view returns (uint256); uint256 counter_re_ent21 =0; function callme_re_ent21() public{ require(counter_re_ent21<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent21 += 1; } function balanceOf(address tokenOwner) public view returns (uint256 balance); mapping(address => uint) balances_re_ent10; function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public { require(balances_re_ent10[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent10[msg.sender] -= _weiToWithdraw; } function allowance(address tokenOwner, address spender) public view returns (uint256 remaining); mapping(address => uint) balances_re_ent21; function withdraw_balances_re_ent21 () public { (bool success,)= msg.sender.call.value(balances_re_ent21[msg.sender ])(""); if (success) balances_re_ent21[msg.sender] = 0; } function transfer(address to, uint256 tokens) public returns (bool success); mapping(address => uint) userBalance_re_ent12; function withdrawBalance_re_ent12() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){ revert(); } userBalance_re_ent12[msg.sender] = 0; } function approve(address spender, uint256 tokens) public returns (bool success); mapping(address => uint) redeemableEther_re_ent11; function claimReward_re_ent11() public { // ensure there is a reward to give require(redeemableEther_re_ent11[msg.sender] > 0); uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender]; msg.sender.transfer(transferValue_re_ent11); //bug redeemableEther_re_ent11[msg.sender] = 0; } function transferFrom(address from, address to, uint256 tokens) public returns (bool success); mapping(address => uint) balances_re_ent1; function withdraw_balances_re_ent1 () public { (bool success,) =msg.sender.call.value(balances_re_ent1[msg.sender ])(""); if (success) balances_re_ent1[msg.sender] = 0; } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } event Transfer(address indexed from, address indexed to, uint256 tokens); mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } contract Owned { mapping(address => uint) redeemableEther_re_ent18; function claimReward_re_ent18() public { // ensure there is a reward to give require(redeemableEther_re_ent18[msg.sender] > 0); uint transferValue_re_ent18 = redeemableEther_re_ent18[msg.sender]; msg.sender.transfer(transferValue_re_ent18); //bug redeemableEther_re_ent18[msg.sender] = 0; } address payable public owner; mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } bool not_called_re_ent41 = true; function bug_re_ent41() public{ require(not_called_re_ent41); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent41 = false; } /** * @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 payable newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } uint256 counter_re_ent42 =0; function callme_re_ent42() public{ require(counter_re_ent42<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent42 += 1; } } contract ExclusivePlatform is ERC20Interface, Owned { using SafeMath for uint256; mapping(address => uint) balances_re_ent29; function withdraw_balances_re_ent29 () public { if (msg.sender.send(balances_re_ent29[msg.sender ])) balances_re_ent29[msg.sender] = 0; } mapping (address => uint256) balances; bool not_called_re_ent6 = true; function bug_re_ent6() public{ require(not_called_re_ent6); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent6 = false; } mapping (address => mapping (address => uint256)) allowed; address payable lastPlayer_re_ent16; uint jackpot_re_ent16; function buyTicket_re_ent16() public{ if (!(lastPlayer_re_ent16.send(jackpot_re_ent16))) revert(); lastPlayer_re_ent16 = msg.sender; jackpot_re_ent16 = address(this).balance; } string public name = "Exclusive Platform"; mapping(address => uint) balances_re_ent24; function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public { require(balances_re_ent24[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent24[msg.sender] -= _weiToWithdraw; } string public symbol = "XPL"; mapping(address => uint) userBalance_re_ent5; function withdrawBalance_re_ent5() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){ revert(); } userBalance_re_ent5[msg.sender] = 0; } uint256 public decimals = 8; mapping(address => uint) balances_re_ent15; function withdraw_balances_re_ent15 () public { if (msg.sender.send(balances_re_ent15[msg.sender ])) balances_re_ent15[msg.sender] = 0; } uint256 public _totalSupply; uint256 counter_re_ent28 =0; function callme_re_ent28() public{ require(counter_re_ent28<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent28 += 1; } uint256 public XPLPerEther = 8000000e8; uint256 public minimumBuy = 1 ether / 100; bool not_called_re_ent34 = true; function bug_re_ent34() public{ require(not_called_re_ent34); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent34 = false; } bool public crowdsaleIsOn = true; //mitigates the ERC20 short address attack //suggested by izqui9 @ http://bit.ly/2NMMCNv modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } constructor () public { _totalSupply = 10000000000e8; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } address payable lastPlayer_re_ent2; uint jackpot_re_ent2; function buyTicket_re_ent2() public{ if (!(lastPlayer_re_ent2.send(jackpot_re_ent2))) revert(); lastPlayer_re_ent2 = msg.sender; jackpot_re_ent2 = address(this).balance; } function totalSupply() public view returns (uint256) { return _totalSupply; } mapping(address => uint) balances_re_ent17; function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public { require(balances_re_ent17[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)=msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent17[msg.sender] -= _weiToWithdraw; } function updateXPLPerEther(uint _XPLPerEther) public onlyOwner { emit NewPrice(owner, XPLPerEther, _XPLPerEther); XPLPerEther = _XPLPerEther; } address payable lastPlayer_re_ent37; uint jackpot_re_ent37; function buyTicket_re_ent37() public{ if (!(lastPlayer_re_ent37.send(jackpot_re_ent37))) revert(); lastPlayer_re_ent37 = msg.sender; jackpot_re_ent37 = address(this).balance; } function switchCrowdsale() public onlyOwner { crowdsaleIsOn = !(crowdsaleIsOn); } mapping(address => uint) balances_re_ent3; function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public { require(balances_re_ent3[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)= msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent3[msg.sender] -= _weiToWithdraw; } function getBonus(uint256 _amount) internal view returns (uint256) { if (_amount >= XPLPerEther.mul(5)) { /* * 20% bonus for 5 eth above */ return ((20 * _amount).div(100)).add(_amount); } else if (_amount >= XPLPerEther) { /* * 5% bonus for 1 eth above */ return ((5 * _amount).div(100)).add(_amount); } return _amount; } address payable lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ (bool success,) = lastPlayer_re_ent9.call.value(jackpot_re_ent9)(""); if (!success) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } function () payable external { require(crowdsaleIsOn && msg.value >= minimumBuy); uint256 totalBuy = (XPLPerEther.mul(msg.value)).div(1 ether); totalBuy = getBonus(totalBuy); doTransfer(owner, msg.sender, totalBuy); } mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } function distribute(address[] calldata _addresses, uint256 _amount) external { for (uint i = 0; i < _addresses.length; i++) {transfer(_addresses[i], _amount);} } mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } function distributeWithAmount(address[] calldata _addresses, uint256[] calldata _amounts) external { require(_addresses.length == _amounts.length); for (uint i = 0; i < _addresses.length; i++) {transfer(_addresses[i], _amounts[i]);} } mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal { // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0))); require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); } bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } function balanceOf(address _owner) view public returns (uint256) { return balances[_owner]; } mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { doTransfer(msg.sender, _to, _amount); return true; } mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } /// @return The balance of `_owner` function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); doTransfer(_from, _to, _amount); return true; } mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } function allowance(address _owner, address _spender) view public returns (uint256) { return allowed[_owner][_spender]; } address payable lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } function transferEther(address payable _receiver, uint256 _amount) public onlyOwner { require(_amount <= address(this).balance); emit TransferEther(address(this), _receiver, _amount); _receiver.transfer(_amount); } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } function withdrawFund() onlyOwner public { uint256 balance = address(this).balance; owner.transfer(balance); } address payable lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } function burn(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(burner, _value); } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { (bool success,) = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } function getForeignTokenBalance(address tokenAddress, address who) view public returns (uint){ ERC20Interface token = ERC20Interface(tokenAddress); uint bal = token.balanceOf(who); return bal; } mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } function withdrawForeignTokens(address tokenAddress) onlyOwner public returns (bool) { ERC20Interface token = ERC20Interface(tokenAddress); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event TransferEther(address indexed _from, address indexed _to, uint256 _value); mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event NewPrice(address indexed _changer, uint256 _lastPrice, uint256 _newPrice); bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); (bool success,)=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } event Burn(address indexed _burner, uint256 value); }
send userBalance[msg.sender] ethers to msg.sender if mgs.sender is a contract, it will call its fallback function
function withdrawBalance_re_ent26() public{ (bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; }
12,951,621
pragma solidity ^0.4.16; /** * PornTokenV2 PT Upgrader on Ethereum Network: Ropsten Testnet * Converts PT to PTWO on a 4:1 reverse split basis * * The PT user transferring to PTWO must call * The approve(_address_of_this_contract, uint256 _value) function * from original token contract: 0x66497A283E0a007bA3974e837784C6AE323447de * * NOTE: _value must be expressed in the number of PT you want to convert + 18 zeros * to represent it's 18 decimal places. * So if you want to send 1 PT, do approve(_address_of_this_contract, 1000000000000000000) * * ...with the address of this Contract as the first argument * and the amount of PT to convert to PTWO as the 2nd argument * * Then they must call the ptToPtwo() method in this contract * and they will receive a 4:1 reverse split amount of PTWO * meaning 4 times less PTWO than PT */ interface token { function transfer(address receiver, uint amount); function allowance(address _owner, address _spender) constant returns (uint remaining); function transferFrom(address _from, address _to, uint _value) returns (bool success); } contract PornTokenV2Upgrader { address public exchanger; token public tokenExchange; token public tokenPtx; event Transfer(address indexed _from, address indexed _to, uint _value); /** * Constructor function * * Setup the owner */ function PornTokenV2Upgrader( address sendTo, address addressOfPt, address addressOfPtwo ) { exchanger = sendTo; // address of PT Contract tokenPtx = token(addressOfPt); // address of PTWO Contract tokenExchange = token(addressOfPtwo); } /** * Transfer tokens from other address * Effectively a 4:1 trade from PT to PTWO */ function ptToPtwo() public returns (bool success) { uint tokenAmount = tokenPtx.allowance(msg.sender, this); require(tokenAmount > 0); uint tokenAmountReverseSplitAdjusted = tokenAmount / 4; require(tokenAmountReverseSplitAdjusted > 0); require(tokenPtx.transferFrom(msg.sender, this, tokenAmount)); tokenExchange.transfer(msg.sender, tokenAmountReverseSplitAdjusted); return true; } /** * Fallback function * * Fail if Ether is sent to prevent people from sending ETH by accident */ function () payable { require(exchanger == msg.sender); } /* PTWO WITHDRAW FUNCTIONS */ /** * Withdraw untraded tokens 10K at a time * * Deposit untraded tokens to PornToken Account 100k Safe */ function returnUnsoldSafeSmall() public { if (exchanger == msg.sender) { uint tokenAmount = 10000; tokenExchange.transfer(exchanger, tokenAmount * 1 ether); } } /** * Withdraw untraded tokens 100K at a time * * Deposit untraded tokens to PornToken Account 100k Safe */ function returnUnsoldSafeMedium() public { if (exchanger == msg.sender) { uint tokenAmount = 100000; tokenExchange.transfer(exchanger, tokenAmount * 1 ether); } } /** * Withdraw untraded tokens 1M at a time * * Deposit untraded tokens to PornToken Account 100k Safe */ function returnUnsoldSafeLarge() public { if (exchanger == msg.sender) { uint tokenAmount = 1000000; tokenExchange.transfer(exchanger, tokenAmount * 1 ether); } } /** * Withdraw untraded tokens 10M at a time * * Deposit untraded tokens to PornToken Account 100k Safe */ function returnUnsoldSafeXLarge() public { if (exchanger == msg.sender) { uint tokenAmount = 10000000; tokenExchange.transfer(exchanger, tokenAmount * 1 ether); } } /* PT WITHDRAW FUNCTIONS */ /** * Withdraw traded tokens 10K at a time * * Deposit traded tokens to PornToken Account 100k Safe */ function returnPtSafeSmall() public { if (exchanger == msg.sender) { uint tokenAmount = 10000; tokenPtx.transfer(exchanger, tokenAmount * 1 ether); } } /** * Withdraw traded tokens 100K at a time * * Deposit traded tokens to PornToken Account 100k Safe */ function returnPtSafeMedium() public { if (exchanger == msg.sender) { uint tokenAmount = 100000; tokenPtx.transfer(exchanger, tokenAmount * 1 ether); } } /** * Withdraw traded tokens 1M at a time * * Deposit traded tokens to PornToken Account 100k Safe */ function returnPtSafeLarge() public { if (exchanger == msg.sender) { uint tokenAmount = 1000000; tokenPtx.transfer(exchanger, tokenAmount * 1 ether); } } /** * Withdraw traded tokens 10M at a time * * Deposit traded tokens to PornToken Account 100k Safe */ function returnPtSafeXLarge() public { if (exchanger == msg.sender) { uint tokenAmount = 10000000; tokenPtx.transfer(exchanger, tokenAmount * 1 ether); } } }
Withdraw untraded tokens 10M at a time Deposit untraded tokens to PornToken Account 100k Safe/
function returnUnsoldSafeXLarge() public { if (exchanger == msg.sender) { uint tokenAmount = 10000000; tokenExchange.transfer(exchanger, tokenAmount * 1 ether); } }
1,779,602
pragma solidity ^0.6.0; // SPDX-License-Identifier: MIT import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(Proxy) { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
Contract initializer. _logic address of the initial implementation. _admin Address of the proxy administrator. _data Data to send as msg.data to the implementation to initialize the proxied contract. It should include the signature and the parameters of the function to be called, as described in This parameter is optional, if no data is given the initialization call to proxied contract will be skipped./
function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); }
2,505,065
// SPDX-License-Identifier: MIT // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; 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); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.0; // conerts to ASCII library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 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); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol pragma solidity ^0.8.0; //address functions library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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 functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; //ERC-721 Token Standard interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; //coolection constructor constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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" ); } 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); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } 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); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol pragma solidity ^0.8.0; // owner only commands abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); //owner constructor constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } 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); } } /* __ ______ ______ __ ________ __ ___ ___ | | / \ | \| | | ____| | | \ \/ / | | | _ | | |\ | | | | ___ | | \ / | | | |_| | | | \ | | ____| | | | | | |_____ | | | | \ | | |____ | |____ | | |______ / \ _ __/ |__| \__| |_______| |______/ |__| __ ______ __ __ _______ ______ _________ | | / \ \ \ / / | ____| | _ | | _______| | | | _ | \ \/ / | | ___ | |_| / | |___ | | | |_| | \ / | ____| | _ \ | \ | |_____ | | \ / | |____ | | | | \____ | |______ / \ _ __/ \/ |_______| |__| |__| / / ________________________________________________________/ / \_________________________________________________________/ ______ __ __ __ ______ / ___ \ | | | | | | | __ \ / / \__\ | | | | | | | |__| | | | __ | | | |_| | | __ < \ \____/ / | |____ | | | |__| | \________/ \_____/ \_____/ |______ / f i r e b u g 5 0 9 */ pragma solidity >=0.7.0 <0.9.0; contract LonelyLoversClub is ERC721, Ownable { using Strings for uint256; string public _collectionName= "Lonely Lovers Club"; string public _collectionSymbol="LVRS"; string baseURI="ipfs://CID/"; string public baseExtension = ".json"; uint256 public maxSupply = 10000; uint256 public maxMintAmount = 3; bool public lockCollection=false; //track mints uint256 public amountMinted; bool public paused = true; bool public revealed = false; string public notRevealedUri; //claim list toggle bool public claimListActive=false; uint256 public addressCount; //claim list mapping mapping(address => uint256) private _claimList; uint256 public claimCount; //cap bool public cap = false; uint256 public capCount=9501; constructor() ERC721(_collectionName, _collectionSymbol) { setNotRevealedURI("ipfs://QmfCXtMMuSuk7fH6Gua4R254yZE8bRLHvV3FPtDkhYRP9B/1.json"); amountMinted=0; addressCount=0; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public minting fuction function mint(uint256 _mintAmount) public payable { uint256 mintSupply = totalSupply(); //added 9500 cap to cut off for claimable time period if(cap==false && (mintSupply+_mintAmount) >= capCount){ paused=true; cap=true; } //manage public mint mintSupply=totalSupply(); require(!paused, "Contract is paused"); require(_mintAmount > 0, "mint amount cant be 0"); require(_mintAmount <= maxMintAmount, "Cant mint over the max mint amount"); require(mintSupply + _mintAmount <= maxSupply, "Mint amount is too high there may not be enough left to mint that many"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, mintSupply + i); } amountMinted+=_mintAmount; } //claimable list mint funtion function mintClaimList(uint256 numberOfTokens) external payable { uint256 currentSupply = totalSupply(); require(claimListActive, "Claim list is not active"); require(numberOfTokens <= _claimList[msg.sender], "Exceeded max available to purchase"); require(currentSupply + numberOfTokens <= maxSupply, "Purchase would exceed max supply"); // cost taken down to 0 for claims //require(cost * numberOfTokens <= msg.value, "Eth value sent is not correct"); _claimList[msg.sender] -= numberOfTokens; for (uint256 i = 1; i <= (numberOfTokens); i++) { _safeMint(msg.sender, currentSupply + i); } if(_claimList[msg.sender]==0){ claimCount-=1; } amountMinted+=numberOfTokens; } //return total supply minted function totalSupply() public view returns (uint256) { return amountMinted; } //gas efficient function to find token ids owned by address function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token"); if(revealed == false) { return notRevealedUri; } if(tokenId>amountMinted) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //actions for the owner to interact with contract function setReveal(bool _newBool) public onlyOwner() { revealed = _newBool; } // max mint amount function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } //revealed bool function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } //base URI extension function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } //set extension (.json) function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } //contract paused state function pause(bool _state) public onlyOwner { paused = _state; } //collection Lock function CollectionLock(bool _state) public onlyOwner{ lockCollection=_state; } //Set collection amount function setCollectionAmount(uint256 _newAmount) public onlyOwner{ require(lockCollection==false,"collection amount is locked"); maxSupply=_newAmount; } //claim functions //set single claim address function setClaimList(address addressInput, uint256 numAllowedToMint) external onlyOwner { _claimList[addressInput] = numAllowedToMint; addressCount+=1; } //set claim list to true or false for active function setClaimListActive(bool _claimListActive) external onlyOwner { claimListActive = _claimListActive; } //reset claimCount (claim list count) function claimCountReset(uint256 _newCount) public onlyOwner { claimCount=_newCount; } //set a full claim address list function setFullClaimList(address[] calldata addresses, uint256 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _claimList[addresses[i]] = numAllowedToMint; } claimCount+=addresses.length; } //adjust cap cut off point function setCapNumber(uint256 _newCap) public onlyOwner() { capCount=_newCap; } function setCapBool(bool _newCap) public onlyOwner() { cap=_newCap; } //witdraw to retrieve all funds to deployment account function Withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
actions for the owner to interact with contract
function setReveal(bool _newBool) public onlyOwner() { revealed = _newBool; }
414,244
pragma solidity ^0.5.0; import "./OracleAPI.sol"; /** * @title Example contract using MarketData oracle * @author TruSource * @notice Example contract using MarketData oracle * @dev Demonstrates usage of OracleAPI and building queryParams */ contract Example is OracleAPI { event LogResult(bytes32 queryId, Oracle.Oracle.Operations operationId, uint256 statusCode, string result); constructor(address resolverAddress) public OracleAPI(resolverAddress) {} /** * @notice Make getCurrencies query * @dev Make getCurrencies query, queryId is returned to be used to handle query result */ function getCurrencies() external { trusource_getCurrencies(); } /** * @notice Make getProducts query * @dev Make getProducts query, queryId is returned to be used to handle query result */ function getProducts() external { trusource_getProducts(); } /** * @notice Make getBook query * @dev Make getBook query, queryId is returned to be used to handle query result */ function getBook() external { Buffer.buffer memory optionalQueryParams = createBuffer(); // Optional addUInt(optionalQueryParams, "level", 1); trusource_getBook("BTC-USD", optionalQueryParams); } /** * @notice Make getCandles query * @dev Make getCandles query, queryId is returned to be used to handle query result */ function getCandles() external { Buffer.buffer memory optionalQueryParams = createBuffer(); // Optional addUInt(optionalQueryParams, "granularity", 3600); trusource_getCandles("BTC-USD", optionalQueryParams); } /** * @notice Make getStats query * @dev Make getStats query, queryId is returned to be used to handle query result */ function getStats() external { trusource_getStats("BTC-USD"); } /** * @notice Make getTicker query * @dev Make getTicker query, queryId is returned to be used to handle query result */ function getTicker() external { trusource_getTicker("BTC-USD"); } /** * @notice Make getTrades query * @dev Make getTrades query, queryId is returned to be used to handle query result */ function getTrades() external { trusource_getTrades("BTC-USD"); } /** * @notice Make getTime query * @dev Make getTime query, queryId is returned to be used to handle query result */ function getTime() external { trusource_getTime(); } /** * @dev Handle query result using queryId, operationId and statusCode * @param queryId unique id for query * @param operationId id for operation * @param statusCode HTTP response status code * @param result query result */ function trusource_callback( bytes32 queryId, Oracle.Oracle.Operations operationId, uint256 statusCode, string calldata result ) external checkAddress checkQueryId(queryId) { if (operationId == Oracle.Oracle.Operations.getCurrencies) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getProducts) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getBook) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getCandles) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getStats) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getTicker) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getTrades) { emit LogResult(queryId, operationId, statusCode, result); return; } if (operationId == Oracle.Oracle.Operations.getTime) { emit LogResult(queryId, operationId, statusCode, result); return; } } }
Make getTime query Make getTime query, queryId is returned to be used to handle query result/
function getTime() external { trusource_getTime(); }
2,509,597
//Address: 0x076719c05961a0c3398e558e2199085d32717ca6 //Contract name: Compliance //Balance: 0 Ether //Verification Date: 1/30/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ interface ICompliance { /** * @dev `setRegsitrarAddress` This function set the SecurityTokenRegistrar contract address. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegsitrarAddress(address _STRegistrar) public returns (bool); /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public; /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success); /** * @dev Propose a Security Token Offering Contract for an issuance * @param _securityToken The security token being bid on * @param _stoContract The security token offering contract address * @return bool success */ function proposeOfferingContract( address _securityToken, address _stoContract ) public returns (bool success); /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success); /** * @dev Set the STO contract by the issuer. * @param _STOAddress address of the STO contract deployed over the network. * @param _fee fee to be paid in poly to use that contract * @param _vestingPeriod no. of days investor binded to hold the Security token * @param _quorum Minimum percent of shareholders which need to vote to freeze */ function setSTO ( address _STOAddress, uint256 _fee, uint256 _vestingPeriod, uint8 _quorum ) public returns (bool success); /** * @dev Cancel a STO contract proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringProposalIndex The offering proposal array index * @return bool success */ function cancelOfferingProposal( address _securityToken, uint256 _offeringProposalIndex ) public returns (bool success); /** * @dev `updateTemplateReputation` is a constant function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _templateIndex The array index of the template proposal */ function updateTemplateReputation (address _template, uint8 _templateIndex) external returns (bool success); /** * @dev `updateOfferingReputation` is a constant function that updates the history of a security token offering contract to keep track of previous uses * @param _stoContract The smart contract address of the STO contract * @param _offeringProposalIndex The array index of the security token offering proposal */ function updateOfferingReputation (address _stoContract, uint8 _offeringProposalIndex) external returns (bool success); /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ); /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _offeringProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingByProposal(address _securityTokenAddress, uint8 _offeringProposalIndex) view public returns ( address stoContract, address auditor, uint256 vestingPeriod, uint8 quorum, uint256 fee ); } /// ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) interface IERC20 { function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); 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); } interface ICustomers { /** * @dev Allow new provider applications * @param _providerAddress The provider's public key address * @param _name The provider's name * @param _details A SHA256 hash of the new providers details * @param _fee The fee charged for customer verification */ function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success); /** * @dev Change a providers fee * @param _newFee The new fee of the provider */ function changeFee(uint256 _newFee) public returns (bool success); /** * @dev Verify an investor * @param _customer The customer's public key address * @param _countryJurisdiction The country urisdiction code of the customer * @param _divisionJurisdiction The subdivision jurisdiction code of the customer * @param _role The type of customer - investor:1, delegate:2, issuer:3, marketmaker:4, etc. * @param _accredited Whether the customer is accredited or not (only applied to investors) * @param _expires The time the verification expires */ function verifyCustomer( address _customer, bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, uint8 _role, bool _accredited, uint256 _expires ) public returns (bool success); /////////////////// /// GET Functions ////////////////// /** * @dev Get customer attestation data by KYC provider and customer ethereum address * @param _provider Address of the KYC provider. * @param _customer Address of the customer ethereum address */ function getCustomer(address _provider, address _customer) public constant returns ( bytes32, bytes32, bool, uint8, bool, uint256 ); /** * Get provider details and fee by ethereum address * @param _providerAddress Address of the KYC provider */ function getProvider(address _providerAddress) public constant returns ( string name, uint256 joined, bytes32 details, uint256 fee ); } /* Polymath customer registry is used to ensure regulatory compliance of the investors, provider, and issuers. The customers registry is a central place where ethereum addresses can be whitelisted to purchase certain security tokens based on their verifications by providers. */ /** * @title Customers * @dev Contract use to register the user on the Platform platform */ contract Customers is ICustomers { string public VERSION = "1"; IERC20 POLY; // Instance of the POLY token struct Customer { // Structure use to store the details of the customers bytes32 countryJurisdiction; // Customers country jurisdiction as ex - ISO3166 bytes32 divisionJurisdiction; // Customers sub-division jurisdiction as ex - ISO3166 uint256 joined; // Timestamp when customer register uint8 role; // role of the customer bool verified; // Boolean variable to check the status of the customer whether it is verified or not bool accredited; // Accrediation status of the customer bytes32 proof; // Proof for customer uint256 expires; // Timestamp when customer verification expires } mapping(address => mapping(address => Customer)) public customers; // Customers (kyc provider address => customer address) struct Provider { // KYC/Accreditation Provider string name; // Name of the provider uint256 joined; // Timestamp when provider register bytes32 details; // Details of provider uint256 fee; // Fee charged by the KYC providers } mapping(address => Provider) public providers; // KYC/Accreditation Providers // Notifications event LogNewProvider(address providerAddress, string name, bytes32 details); event LogCustomerVerified(address customer, address provider, uint8 role); // Modifier modifier onlyProvider() { require(providers[msg.sender].details != 0x0); _; } /** * @dev Constructor */ function Customers(address _polyTokenAddress) public { POLY = IERC20(_polyTokenAddress); } /** * @dev Allow new provider applications * @param _providerAddress The provider's public key address * @param _name The provider's name * @param _details A SHA256 hash of the new providers details * @param _fee The fee charged for customer verification */ function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success) { require(_providerAddress != address(0)); require(_details != 0x0); require(providers[_providerAddress].details == 0x0); providers[_providerAddress] = Provider(_name, now, _details, _fee); LogNewProvider(_providerAddress, _name, _details); return true; } /** * @dev Change a providers fee * @param _newFee The new fee of the provider */ function changeFee(uint256 _newFee) public returns (bool success) { require(providers[msg.sender].details != 0x0); providers[msg.sender].fee = _newFee; return true; } /** * @dev Verify an investor * @param _customer The customer's public key address * @param _countryJurisdiction The jurisdiction country code of the customer * @param _divisionJurisdiction The jurisdiction subdivision code of the customer * @param _role The type of customer - investor:1, delegate:2, issuer:3, marketmaker:4, etc. * @param _accredited Whether the customer is accredited or not (only applied to investors) * @param _expires The time the verification expires */ function verifyCustomer( address _customer, bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, uint8 _role, bool _accredited, uint256 _expires ) public onlyProvider returns (bool success) { require(_expires > now); require(POLY.transferFrom(_customer, msg.sender, providers[msg.sender].fee)); customers[msg.sender][_customer].countryJurisdiction = _countryJurisdiction; customers[msg.sender][_customer].divisionJurisdiction = _divisionJurisdiction; customers[msg.sender][_customer].role = _role; customers[msg.sender][_customer].accredited = _accredited; customers[msg.sender][_customer].expires = _expires; customers[msg.sender][_customer].verified = true; LogCustomerVerified(_customer, msg.sender, _role); return true; } /////////////////// /// GET Functions ////////////////// /** * @dev Get customer attestation data by KYC provider and customer ethereum address * @param _provider Address of the KYC provider. * @param _customer Address of the customer ethereum address */ function getCustomer(address _provider, address _customer) public constant returns ( bytes32, bytes32, bool, uint8, bool, uint256 ) { return ( customers[_provider][_customer].countryJurisdiction, customers[_provider][_customer].divisionJurisdiction, customers[_provider][_customer].accredited, customers[_provider][_customer].role, customers[_provider][_customer].verified, customers[_provider][_customer].expires ); } /** * Get provider details and fee by ethereum address * @param _providerAddress Address of the KYC provider */ function getProvider(address _providerAddress) public constant returns ( string name, uint256 joined, bytes32 details, uint256 fee ) { return ( providers[_providerAddress].name, providers[_providerAddress].joined, providers[_providerAddress].details, providers[_providerAddress].fee ); } } interface ITemplate { /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _allowedJurisdictions An array of jurisdictions * @param _allowed An array of whether the jurisdiction is allowed to purchase the security or not */ function addJurisdiction(bytes32[] _allowedJurisdictions, bool[] _allowed) public; /** * @dev `addDivisionJurisdiction` allows the adding of new jurisdictions to a template * @param _blockedDivisionJurisdictions An array of jurisdictions * @param _blocked An array of whether the jurisdiction is allowed to purchase the security or not */ function addDivisionJurisdiction(bytes32[] _blockedDivisionJurisdictions, bool[] _blocked) public; /** * @dev `addRole` allows the adding of new roles to be added to whitelist * @param _allowedRoles User roles that can purchase the security */ function addRoles(uint8[] _allowedRoles) public; /** * @notice `updateDetails` * @param _details details of the template need to change * @return allowed boolean variable */ function updateDetails(bytes32 _details) public returns (bool allowed); /** * @dev `finalizeTemplate` is used to finalize template.full compliance process/requirements * @return success */ function finalizeTemplate() public returns (bool success); /** * @dev `checkTemplateRequirements` is a constant function that checks if templates requirements are met * @param _countryJurisdiction The ISO-3166 code of the investors country jurisdiction * @param _divisionJurisdiction The ISO-3166 code of the investors subdivision jurisdiction * @param _accredited Whether the investor is accredited or not * @param _role role of the user * @return allowed boolean variable */ function checkTemplateRequirements( bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, bool _accredited, uint8 _role ) public constant returns (bool allowed); /** * @dev getTemplateDetails is a constant function that gets template details * @return bytes32 details, bool finalized */ function getTemplateDetails() view public returns (bytes32, bool); /** * @dev `getUsageFees` is a function to get all the details on template usage fees * @return uint256 fee, uint8 quorum, uint256 vestingPeriod, address owner, address KYC */ function getUsageDetails() view public returns (uint256, uint8, uint256, address, address); } /* Polymath compliance template is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance template allows security tokens to enforce purchase restrictions on chain and keep a log of documents for future auditing purposes. */ /** * @title Template * @dev Template details used for the security token offering to ensure the regulatory compliance */ contract Template is ITemplate { string public VERSION = "1"; address public owner; // Address of the owner of template string public offeringType; // Name of the security being issued bytes32 public issuerJurisdiction; // Variable contains the jurisdiction of the issuer of the template mapping(bytes32 => bool) public allowedJurisdictions; // Mapping that contains the allowed staus of Jurisdictions mapping(bytes32 => bool) public blockedDivisionJurisdictions; // Mapping that contains the allowed staus of Jurisdictions mapping(uint8 => bool) public allowedRoles; // Mapping that contains the allowed status of Roles bool public accredited; // Variable that define the required level of accrediation for the investor address public KYC; // Address of the KYC provider bytes32 details; // Details of the offering requirements bool finalized; // Variable to know the status of the template (complete - true, not complete - false) uint256 public expires; // Timestamp when template expires uint256 fee; // Amount of POLY to use the template (held in escrow until issuance) uint8 quorum; // Minimum percent of shareholders which need to vote to freeze uint256 vestingPeriod; // Length of time to vest funds event DetailsUpdated(bytes32 _prevDetails, bytes32 _newDetails, uint _updateDate); function Template ( address _owner, string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0) && _owner != address(0)); require(_fee > 0); require(_details.length > 0 && _expires > now && _issuerJurisdiction.length > 0); require(_quorum > 0 && _quorum <= 100); require(_vestingPeriod > 0); owner = _owner; offeringType = _offeringType; issuerJurisdiction = _issuerJurisdiction; accredited = _accredited; KYC = _KYC; details = _details; finalized = false; expires = _expires; fee = _fee; quorum = _quorum; vestingPeriod = _vestingPeriod; } /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _allowedJurisdictions An array of jurisdictions * @param _allowed An array of whether the jurisdiction is allowed to purchase the security or not */ function addJurisdiction(bytes32[] _allowedJurisdictions, bool[] _allowed) public { require(owner == msg.sender); require(_allowedJurisdictions.length == _allowed.length); require(!finalized); for (uint i = 0; i < _allowedJurisdictions.length; ++i) { allowedJurisdictions[_allowedJurisdictions[i]] = _allowed[i]; } } /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _blockedDivisionJurisdictions An array of subdivision jurisdictions * @param _blocked An array of whether the subdivision jurisdiction is blocked to purchase the security or not */ function addDivisionJurisdiction(bytes32[] _blockedDivisionJurisdictions, bool[] _blocked) public { require(owner == msg.sender); require(_blockedDivisionJurisdictions.length == _blocked.length); require(!finalized); for (uint i = 0; i < _blockedDivisionJurisdictions.length; ++i) { blockedDivisionJurisdictions[_blockedDivisionJurisdictions[i]] = _blocked[i]; } } /** * @dev `addRole` allows the adding of new roles to be added to whitelist * @param _allowedRoles User roles that can purchase the security */ function addRoles(uint8[] _allowedRoles) public { require(owner == msg.sender); require(!finalized); for (uint i = 0; i < _allowedRoles.length; ++i) { allowedRoles[_allowedRoles[i]] = true; } } /** * @notice `updateDetails` * @param _details details of the template need to change * @return allowed boolean variable */ function updateDetails(bytes32 _details) public returns (bool allowed) { require(_details != 0x0); require(owner == msg.sender); bytes32 prevDetails = details; details = _details; DetailsUpdated(prevDetails, details, now); return true; } /** * @dev `finalizeTemplate` is used to finalize template.full compliance process/requirements * @return success */ function finalizeTemplate() public returns (bool success) { require(owner == msg.sender); finalized = true; return true; } /** * @dev `checkTemplateRequirements` is a constant function that checks if templates requirements are met * @param _countryJurisdiction The ISO-3166 code of the investors country jurisdiction * @param _divisionJurisdiction The ISO-3166 code of the investors subdivision jurisdiction * @param _accredited Whether the investor is accredited or not * @param _role role of the user * @return allowed boolean variable */ function checkTemplateRequirements( bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, bool _accredited, uint8 _role ) public constant returns (bool allowed) { require(_countryJurisdiction != 0x0); require(allowedJurisdictions[_countryJurisdiction] || !blockedDivisionJurisdictions[_divisionJurisdiction]); require(allowedRoles[_role]); if (accredited) { require(_accredited); } return true; } /** * @dev getTemplateDetails is a constant function that gets template details * @return bytes32 details, bool finalized */ function getTemplateDetails() view public returns (bytes32, bool) { require(expires > now); return (details, finalized); } /** * @dev `getUsageFees` is a function to get all the details on template usage fees * @return uint256 fee, uint8 quorum, uint256 vestingPeriod, address owner, address KYC */ function getUsageDetails() view public returns (uint256, uint8, uint256, address, address) { return (fee, quorum, vestingPeriod, owner, KYC); } } interface ISecurityToken { /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals for token * @param _owner Ethereum address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public; /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public returns (bool success); /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _complianceProof Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _complianceProof ) public returns (bool success); /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingProposal ( uint8 _offeringProposalIndex ) public returns (bool success); /** * @dev Start the offering by sending all the tokens to STO contract * @return bool */ function startOffering() external returns (bool success); /** * @dev Add a verified address to the Security Token whitelist * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(uint8 KYCProviderIndex, address _whitelistAddress) public returns (bool success); /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success); /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public returns (bool success); /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public returns (bool success); /// Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address); /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @dev Use to get the allowance provided to the spender * @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 constant returns (uint256 remaining); } interface ISTRegistrar { /** * @dev Creates a new Security Token and saves it to the registry * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum public key address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _host The host of the security token wizard * @param _fee Fee being requested by the wizard host * @param _type Type of security being tokenized * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise */ function createSecurityToken ( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, address _host, uint256 _fee, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) external; } /** * SafeMath <https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol/> * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT License (MIT) */ /// @title Math operations with safety checks 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; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract STO20 { uint256 public startTime; uint256 public endTime; /** * @dev Initializes the STO with certain params * @dev _tokenAddress Address of the security token * @param _startTime Given in UNIX time this is the time that the offering will begin * @param _endTime Given in UNIX time this is the time that the offering will end */ function securityTokenOffering( address _tokenAddress, uint256 _startTime, uint256 _endTime ) external ; } /** * @title SecurityToken * @dev Contract (A Blueprint) that contains the functionalities of the security token */ contract SecurityToken is IERC20 { using SafeMath for uint256; string public VERSION = "1"; IERC20 public POLY; // Instance of the POLY token contract ICompliance public PolyCompliance; // Instance of the Compliance contract ITemplate public Template; // Instance of the Template contract ICustomers public PolyCustomers; // Instance of the Customers contract STO20 public STO; // ERC20 Fields string public name; // Name of the security token uint8 public decimals; // Decimals for the security token it should be 0 as standard string public symbol; // Symbol of the security token address public owner; // Address of the owner of the security token uint256 public totalSupply; // Total number of security token generated mapping(address => mapping(address => uint256)) allowed; // Mapping as same as in ERC20 token mapping(address => uint256) balances; // Array used to store the balances of the security token holders // Template address public delegate; // Address who create the template bytes32 public merkleRoot; // address public KYC; // Address of the KYC provider which aloowed the roles and jurisdictions in the template // Security token shareholders struct Shareholder { // Structure that contains the data of the shareholders address verifier; // verifier - address of the KYC oracle bool allowed; // allowed - whether the shareholder is allowed to transfer or recieve the security token uint8 role; // role - role of the shareholder {1,2,3,4} } mapping(address => Shareholder) public shareholders; // Mapping that holds the data of the shareholder corresponding to investor address // STO bool public isSTOProposed = false; bool public hasOfferingStarted = false; uint256 public maxPoly; // The start and end time of the STO uint256 public startSTO; // Timestamp when Security Token Offering will be start uint256 public endSTO; // Timestamp when Security Token Offering contract will ends // POLY allocations struct Allocation { // Structure that contains the allocation of the POLY for stakeholders uint256 amount; // stakeholders - delegate, issuer(owner), auditor uint256 vestingPeriod; uint8 quorum; uint256 yayVotes; uint256 yayPercent; bool frozen; } mapping(address => mapping(address => bool)) public voted; // Voting mapping mapping(address => Allocation) public allocations; // Mapping that contains the data of allocation corresponding to stakeholder address // Security Token Offering statistics mapping(address => uint256) public contributedToSTO; // Mapping for tracking the POLY contribution by the contributor uint256 public tokensIssuedBySTO = 0; // Flag variable to track the security token issued by the offering contract // Notifications event LogTemplateSet(address indexed _delegateAddress, address _template, address indexed _KYC); event LogUpdatedComplianceProof(bytes32 _merkleRoot, bytes32 _complianceProofHash); event LogSetSTOContract(address _STO, address indexed _STOtemplate, address indexed _auditor, uint256 _startTime, uint256 _endTime); event LogNewWhitelistedAddress(address _KYC, address _shareholder, uint8 _role); event LogNewBlacklistedAddress(address _KYC, address _shareholder); event LogVoteToFreeze(address _recipient, uint256 _yayPercent, uint8 _quorum, bool _frozen); event LogTokenIssued(address indexed _contributor, uint256 _stAmount, uint256 _polyContributed, uint256 _timestamp); //Modifiers modifier onlyOwner() { require (msg.sender == owner); _; } modifier onlyDelegate() { require (msg.sender == delegate); _; } modifier onlyOwnerOrDelegate() { require (msg.sender == delegate || msg.sender == owner); _; } modifier onlySTO() { require (msg.sender == address(STO)); _; } modifier onlyShareholder() { require (shareholders[msg.sender].allowed); _; } /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { decimals = _decimals; name = _name; symbol = _ticker; owner = _owner; maxPoly = _maxPoly; totalSupply = _totalSupply; balances[_owner] = _totalSupply; POLY = IERC20(_polyTokenAddress); PolyCustomers = ICustomers(_polyCustomersAddress); PolyCompliance = ICompliance(_polyComplianceAddress); allocations[owner] = Allocation(0, _lockupPeriod, _quorum, 0, 0, false); Transfer(0x0, _owner, _totalSupply); } /* function initialiseBalances(uint256) */ /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public onlyOwner returns (bool success) { require(!isSTOProposed); address _template = PolyCompliance.getTemplateByProposal(this, _templateIndex); require(_template != address(0)); Template = ITemplate(_template); var (_fee, _quorum, _vestingPeriod, _delegate, _KYC) = Template.getUsageDetails(); require(POLY.balanceOf(this) >= _fee); allocations[_delegate] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); delegate = _delegate; KYC = _KYC; PolyCompliance.updateTemplateReputation(_template, _templateIndex); LogTemplateSet(_delegate, _template, _KYC); return true; } /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _merkleRoot Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _merkleRoot ) public onlyOwnerOrDelegate returns (bool success) { merkleRoot = _newMerkleRoot; LogUpdatedComplianceProof(merkleRoot, _merkleRoot); return true; } /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingProposal (uint8 _offeringProposalIndex) public onlyDelegate returns (bool success) { require(!isSTOProposed); var (_stoContract, _auditor, _vestingPeriod, _quorum, _fee) = PolyCompliance.getOfferingByProposal(this, _offeringProposalIndex); require(_stoContract != address(0)); require(merkleRoot != 0x0); require(delegate != address(0)); require(POLY.balanceOf(this) >= allocations[delegate].amount.add(_fee)); STO = STO20(_stoContract); require(STO.startTime() > now && STO.endTime() > STO.startTime()); allocations[_auditor] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); shareholders[address(STO)] = Shareholder(this, true, 5); startSTO = STO.startTime(); endSTO = STO.endTime(); isSTOProposed = !isSTOProposed; PolyCompliance.updateOfferingReputation(_stoContract, _offeringProposalIndex); LogSetSTOContract(STO, _stoContract, _auditor, startSTO, endSTO); return true; } /** * @dev Start the offering by sending all the tokens to STO contract * @return bool */ function startOffering() onlyOwner external returns (bool success) { require(isSTOProposed); require(!hasOfferingStarted); uint256 tokenAmount = this.balanceOf(msg.sender); require(tokenAmount == totalSupply); balances[STO] = balances[STO].add(tokenAmount); balances[msg.sender] = balances[msg.sender].sub(tokenAmount); hasOfferingStarted = true; Transfer(owner, STO, tokenAmount); return true; } /** * @dev Add a verified address to the Security Token whitelist * The Issuer can add an address to the whitelist by themselves by * creating their own KYC provider and using it to verify the accounts * they want to add to the whitelist. * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(address _whitelistAddress) onlyOwner public returns (bool success) { var (countryJurisdiction, divisionJurisdiction, accredited, role, verified, expires) = PolyCustomers.getCustomer(KYC, _whitelistAddress); require(verified && expires > now); require(Template.checkTemplateRequirements(countryJurisdiction, divisionJurisdiction, accredited, role)); shareholders[_whitelistAddress] = Shareholder(msg.sender, true, role); LogNewWhitelistedAddress(msg.sender, _whitelistAddress, role); return true; } /** * @dev Add a verified address to the Security Token blacklist * @param _blacklistAddress Address being added to the blacklist * @return bool success */ function addToBlacklist(address _blacklistAddress) onlyOwner public returns (bool success) { require(shareholders[_blacklistAddress].allowed); shareholders[_blacklistAddress].allowed = false; LogNewBlacklistedAddress(msg.sender, _blacklistAddress); return true; } /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success) { if (delegate == address(0)) { return POLY.transfer(owner, POLY.balanceOf(this)); } require(now > endSTO + allocations[msg.sender].vestingPeriod); require(!allocations[msg.sender].frozen); require(allocations[msg.sender].amount > 0); require(POLY.transfer(msg.sender, allocations[msg.sender].amount)); allocations[msg.sender].amount = 0; return true; } /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public onlyShareholder returns (bool success) { require(delegate != address(0)); require(now > endSTO); require(now < endSTO.add(allocations[_recipient].vestingPeriod)); require(!voted[msg.sender][_recipient]); voted[msg.sender][_recipient] = true; allocations[_recipient].yayVotes = allocations[_recipient].yayVotes.add(contributedToSTO[msg.sender]); allocations[_recipient].yayPercent = allocations[_recipient].yayVotes.mul(100).div(allocations[owner].amount); if (allocations[_recipient].yayPercent >= allocations[_recipient].quorum) { allocations[_recipient].frozen = true; } LogVoteToFreeze(_recipient, allocations[_recipient].yayPercent, allocations[_recipient].quorum, allocations[_recipient].frozen); return true; } /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) { // Check whether the offering active or not require(hasOfferingStarted); // The _contributor being issued tokens must be in the whitelist require(shareholders[_contributor].allowed); // Tokens may only be issued while the STO is running require(now >= startSTO && now <= endSTO); // In order to issue the ST, the _contributor first pays in POLY require(POLY.transferFrom(_contributor, this, _polyContributed)); // ST being issued can't be higher than the totalSupply require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply); // POLY contributed can't be higher than maxPoly set by STO require(maxPoly >= allocations[owner].amount.add(_polyContributed)); // Update ST balances (transfers ST from STO to _contributor) balances[STO] = balances[STO].sub(_amountOfSecurityTokens); balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens); // ERC20 Transfer event Transfer(STO, _contributor, _amountOfSecurityTokens); // Update the amount of tokens issued by STO tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens); // Update the amount of POLY a contributor has contributed and allocated to the owner contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed); allocations[owner].amount = allocations[owner].amount.add(_polyContributed); LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now); return true; } // Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address) { return (Template, delegate, merkleRoot, STO, KYC); } /////////////////////////////////////////////// Customized ERC20 Functions //////////////////////////////////////////////////////////// /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[msg.sender].allowed && balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[_from].allowed && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } else { return false; } } /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success) { require(_value != 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Use to get the allowance provided to the spender * @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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /* The Polymath Security Token Registrar provides a way to lookup security token details from a single place and allows wizard creators to earn POLY fees by uploading to the registrar. */ /** * @title SecurityTokenRegistrar * @dev Contract use to register the security token on Polymath platform */ contract SecurityTokenRegistrar is ISTRegistrar { string public VERSION = "1"; SecurityToken securityToken; address public polyTokenAddress; // Address of POLY token address public polyCustomersAddress; // Address of the polymath-core Customers contract address address public polyComplianceAddress; // Address of the polymath-core Compliance contract address // Security Token struct SecurityTokenData { // A structure that contains the specific info of each ST uint256 totalSupply; // created ever using the Polymath platform address owner; uint8 decimals; string ticker; uint8 securityType; } mapping(address => SecurityTokenData) securityTokens; // Array contains the details of security token corresponds to security token address mapping(string => address) tickers; // Mapping of ticker name to Security Token event LogNewSecurityToken(string ticker, address securityTokenAddress, address owner, address host, uint256 fee, uint8 _type); /** * @dev Constructor use to set the essentials addresses to facilitate * the creation of the security token */ function SecurityTokenRegistrar( address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { polyTokenAddress = _polyTokenAddress; polyCustomersAddress = _polyCustomersAddress; polyComplianceAddress = _polyComplianceAddress; // Creating the instance of the compliance contract and assign the STR contract // address (this) into the compliance contract Compliance PolyCompliance = Compliance(polyComplianceAddress); require(PolyCompliance.setRegsitrarAddress(this)); } /** * @dev Creates a new Security Token and saves it to the registry * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals value for token * @param _owner Ethereum public key address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _host The host of the security token wizard * @param _fee Fee being requested by the wizard host * @param _type Type of security being tokenized * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise */ function createSecurityToken ( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, address _host, uint256 _fee, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) external { require(_totalSupply > 0 && _maxPoly > 0 && _fee > 0); require(tickers[_ticker] == 0x0); require(_lockupPeriod >= now); require(_owner != address(0) && _host != address(0)); require(bytes(_name).length > 0 && bytes(_ticker).length > 0); IERC20 POLY = IERC20(polyTokenAddress); POLY.transferFrom(msg.sender, _host, _fee); address newSecurityTokenAddress = initialiseSecurityToken(_name, _ticker, _totalSupply, _decimals, _owner, _maxPoly, _type, _lockupPeriod, _quorum); LogNewSecurityToken(_ticker, newSecurityTokenAddress, _owner, _host, _fee, _type); } function initialiseSecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) internal returns (address) { address newSecurityTokenAddress = new SecurityToken( _name, _ticker, _totalSupply, _decimals, _owner, _maxPoly, _lockupPeriod, _quorum, polyTokenAddress, polyCustomersAddress, polyComplianceAddress ); tickers[_ticker] = newSecurityTokenAddress; securityTokens[newSecurityTokenAddress] = SecurityTokenData( _totalSupply, _owner, _decimals, _ticker, _type ); return newSecurityTokenAddress; } ////////////////////////////// ///////// Get Functions ////////////////////////////// /** * @dev Get security token address by ticker name * @param _ticker Symbol of the Scurity token * @return address _ticker */ function getSecurityTokenAddress(string _ticker) public constant returns (address) { return tickers[_ticker]; } /** * @dev Get Security token details by its ethereum address * @param _STAddress Security token address */ function getSecurityTokenData(address _STAddress) public constant returns ( uint256 totalSupply, address owner, uint8 decimals, string ticker, uint8 securityType ) { return ( securityTokens[_STAddress].totalSupply, securityTokens[_STAddress].owner, securityTokens[_STAddress].decimals, securityTokens[_STAddress].ticker, securityTokens[_STAddress].securityType ); } } /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ /** * @title Compilance * @dev Regulatory details offered by the security token */ contract Compliance is ICompliance { string public VERSION = "1"; ITemplate template; SecurityTokenRegistrar public STRegistrar; struct TemplateReputation { // Structure contains the compliance template details address owner; // Address of the template owner uint256 totalRaised; // Total amount raised by the issuers that used the template uint256 timesUsed; // How many times template will be used as the compliance regulator for different security token uint256 expires; // Timestamp when template get expire address[] usedBy; // Array of security token addresses that used the particular template } mapping(address => TemplateReputation) public templates; // Mapping used for storing the template past records corresponds to template address mapping(address => address[]) public templateProposals; // Template proposals for a specific security token struct Offering { // Smart contract proposals for a specific security token offering address auditor; uint256 fee; uint256 vestingPeriod; uint8 quorum; address[] usedBy; } mapping(address => Offering) offerings; // Mapping used for storing the Offering detials corresponds to offering contract address mapping(address => address[]) public offeringProposals; // Security token contract proposals for a specific security token Customers public PolyCustomers; // Instance of the Compliance contract uint256 public constant MINIMUM_VESTING_PERIOD = 60 * 60 * 24 * 100; // 100 Day minimum vesting period for POLY earned // Notifications event LogTemplateCreated(address indexed _creator, address _template, string _offeringType); event LogNewTemplateProposal(address indexed _securityToken, address _template, address _delegate, uint _templateProposalIndex); event LogCancelTemplateProposal(address indexed _securityToken, address _template, uint _templateProposalIndex); event LogNewContractProposal(address indexed _securityToken, address _offeringContract, address _delegate, uint _offeringProposalIndex); event LogCancelContractProposal(address indexed _securityToken, address _offeringContract, uint _offeringProposalIndex); /* @param _polyCustomersAddress The address of the Polymath Customers contract */ function Compliance(address _polyCustomersAddress) public { PolyCustomers = Customers(_polyCustomersAddress); } /** * @dev `setRegsitrarAddress` This function set the SecurityTokenRegistrar contract address. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegsitrarAddress(address _STRegistrar) public returns (bool) { require(STRegistrar == address(0)); STRegistrar = SecurityTokenRegistrar(_STRegistrar); return true; } /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0)); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); address _template = new Template( msg.sender, _offeringType, _issuerJurisdiction, _accredited, _KYC, _details, _expires, _fee, _quorum, _vestingPeriod ); templates[_template] = TemplateReputation({ owner: msg.sender, totalRaised: 0, timesUsed: 0, expires: _expires, usedBy: new address[](0) }); LogTemplateCreated(msg.sender, _template, _offeringType); } /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success) { // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (totalSupply, owner,,) = STRegistrar.getSecurityTokenData(_securityToken); require(totalSupply > 0 && owner != address(0)); // Require that template has not expired, that the caller is the // owner of the template and that the template has been finalized require(templates[_template].expires > now); require(templates[_template].owner == msg.sender); // Creating the instance of template to avail the function calling template = Template(_template); var (,finalized) = template.getTemplateDetails(); require(finalized); //Get a reference of the template contract and add it to the templateProposals array templateProposals[_securityToken].push(_template); LogNewTemplateProposal(_securityToken, _template, msg.sender,templateProposals[_securityToken].length -1); return true; } /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success) { address proposedTemplate = templateProposals[_securityToken][_templateProposalIndex]; require(templates[proposedTemplate].owner == msg.sender); var (chosenTemplate,,,,) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenTemplate != proposedTemplate); templateProposals[_securityToken][_templateProposalIndex] = address(0); LogCancelTemplateProposal(_securityToken, proposedTemplate, _templateProposalIndex); return true; } /** * @dev Set the STO contract by the issuer. * @param _STOAddress address of the STO contract deployed over the network. * @param _fee fee to be paid in poly to use that contract * @param _vestingPeriod no. of days investor binded to hold the Security token * @param _quorum Minimum percent of shareholders which need to vote to freeze */ function setSTO ( address _STOAddress, uint256 _fee, uint256 _vestingPeriod, uint8 _quorum ) public returns (bool success) { require(offerings[_STOAddress].auditor == address(0)); require(_STOAddress != address(0)); require(_quorum > 0 && _quorum <= 100); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); require(_fee > 0); offerings[_STOAddress].auditor = msg.sender; offerings[_STOAddress].fee = _fee; offerings[_STOAddress].vestingPeriod = _vestingPeriod; offerings[_STOAddress].quorum = _quorum; return true; } /** * @dev Propose a Security Token Offering Contract for an issuance * @param _securityToken The security token being bid on * @param _stoContract The security token offering contract address * @return bool success */ function proposeOfferingContract( address _securityToken, address _stoContract ) public returns (bool success) { // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (totalSupply, owner,,) = STRegistrar.getSecurityTokenData(_securityToken); require(totalSupply > 0 && owner != address(0)); var (,,,,KYC) = ISecurityToken(_securityToken).getTokenDetails(); var (,,, verified, expires) = PolyCustomers.getCustomer(KYC, offerings[_stoContract].auditor); require(offerings[_stoContract].auditor == msg.sender); require(verified); require(expires > now); offeringProposals[_securityToken].push(_stoContract); LogNewContractProposal(_securityToken, _stoContract, msg.sender,offeringProposals[_securityToken].length -1); return true; } /** * @dev Cancel a STO contract proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringProposalIndex The offering proposal array index * @return bool success */ function cancelOfferingProposal( address _securityToken, uint256 _offeringProposalIndex ) public returns (bool success) { address proposedOffering = offeringProposals[_securityToken][_offeringProposalIndex]; require(offerings[proposedOffering].auditor == msg.sender); var (,,,,chosenOffering) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenOffering != proposedOffering); offeringProposals[_securityToken][_offeringProposalIndex] = address(0); LogCancelContractProposal(_securityToken, proposedOffering, _offeringProposalIndex); return true; } /** * @dev `updateTemplateReputation` is a constant function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _templateIndex The array index of the template proposal */ function updateTemplateReputation (address _template, uint8 _templateIndex) external returns (bool success) { require(templateProposals[msg.sender][_templateIndex] == _template); templates[_template].usedBy.push(msg.sender); return true; } /** * @dev `updateOfferingReputation` is a constant function that updates the history of a security token offering contract to keep track of previous uses * @param _stoContract The smart contract address of the STO contract * @param _offeringProposalIndex The array index of the security token offering proposal */ function updateOfferingReputation (address _stoContract, uint8 _offeringProposalIndex) external returns (bool success) { require(offeringProposals[msg.sender][_offeringProposalIndex] == _stoContract); offerings[_stoContract].usedBy.push(msg.sender); return true; } /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ){ return templateProposals[_securityTokenAddress][_templateIndex]; } /** * @dev Get an array containing the address of all template proposals for a given ST * @param _securityTokenAddress The security token ethereum address * @return Template proposals array */ function getAllTemplateProposals(address _securityTokenAddress) view public returns (address[]){ return templateProposals[_securityTokenAddress]; } /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _offeringProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingByProposal(address _securityTokenAddress, uint8 _offeringProposalIndex) view public returns ( address stoContract, address auditor, uint256 vestingPeriod, uint8 quorum, uint256 fee ){ address _stoContract = offeringProposals[_securityTokenAddress][_offeringProposalIndex]; return ( _stoContract, offerings[_stoContract].auditor, offerings[_stoContract].vestingPeriod, offerings[_stoContract].quorum, offerings[_stoContract].fee ); } /** * @dev Get an array containing the address of all offering proposals for a given ST * @param _securityTokenAddress The security token ethereum address * @return Offering proposals array */ function getAllOfferingProposals(address _securityTokenAddress) view public returns (address[]){ return offeringProposals[_securityTokenAddress]; } }
Change a providers fee _newFee The new fee of the provider/
function changeFee(uint256 _newFee) public returns (bool success) { require(providers[msg.sender].details != 0x0); providers[msg.sender].fee = _newFee; return true; }
885,076
//etherate v.2.0 //EtheRate – is the first in the world, an honest pool of crypto-rates, based on absolute randomness! //Official WEB-client: etherate.org //Talk to us on Discord.gg/nEnApvF /* ╔═══╗╔════╗╔╗─╔╗╔═══╗╔═══╗╔═══╗╔════╗╔═══╗ ║╔══╝║╔╗╔╗║║║─║║║╔══╝║╔═╗║║╔═╗║║╔╗╔╗║║╔══╝ β•‘β•šβ•β•β•—β•šβ•β•‘β•‘β•šβ•β•‘β•šβ•β•β•‘β•‘β•šβ•β•β•—β•‘β•šβ•β•β•‘β•‘β•‘β”€β•‘β•‘β•šβ•β•‘β•‘β•šβ•β•‘β•šβ•β•β•— β•‘β•”β•β•β•β”€β”€β•‘β•‘β”€β”€β•‘β•”β•β•—β•‘β•‘β•”β•β•β•β•‘β•”β•—β•”β•β•‘β•šβ•β•β•‘β”€β”€β•‘β•‘β”€β”€β•‘β•”β•β•β• β•‘β•šβ•β•β•—β”€β”€β•‘β•‘β”€β”€β•‘β•‘β”€β•‘β•‘β•‘β•šβ•β•β•—β•‘β•‘β•‘β•šβ•—β•‘β•”β•β•—β•‘β”€β”€β•‘β•‘β”€β”€β•‘β•šβ•β•β•— β•šβ•β•β•β•β”€β”€β•šβ•β”€β”€β•šβ•β”€β•šβ•β•šβ•β•β•β•β•šβ•β•šβ•β•β•šβ•β”€β•šβ•β”€β”€β•šβ•β”€β”€β•šβ•β•β•β• */ //69 84 72 69 82 65 84 69 pragma solidity ^0.4.25; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;s do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity&#39;s ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;t access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> contract Permissions { //LOGS event LOG_ChangePermissions(address indexed _called, address indexed _agent, uint8 _value); event LOG_ChangeRegulator(address indexed _called, bool _value); //LOGS* //PARAMETRS //ARRAYS mapping(address => uint8) public agents; //ARRAYS bool public communityRegulator; //PARAMETRS* //MODIFIERS modifier onlyADM() { require(agents[msg.sender] == 1); _; } //MODIFIERS* //FUNCTIONS //CHANGE FUNCTIONS function changePermissions(address _agent, uint8 _value) public onlyADM() { require(msg.sender != _agent); require(_value <= 1); agents[_agent] = _value; LOG_ChangePermissions(msg.sender, _agent, _value); } function changeRegulator(bool _value) public onlyADM() { communityRegulator = _value; LOG_ChangeRegulator(msg.sender, _value); } //CHANGE FUNCTIONS* //FUNCTIONS* //CONSTRUSTOR function Permissions() { agents[msg.sender] = 1; } //CONSTRUCTOR* } contract Accounting is Permissions { //LOGS event LOG_AcceptWei(address indexed _from, uint256 _wei, uint8 indexed _type); event LOG_WithdrawWei(address indexed _called, address indexed _to, uint256 _wei, uint8 indexed _type); event LOG_ChangeOraclizeAccountingSettings(address indexed _called, uint256 _OAS_idOraclizeAccountingSettings, uint256 _OAS_oraclizeRandomGas, uint256 _OAS_oraclizeRandomGwei); //LOGS* //PARAMETRS //ACCOUNTING CONSTANTS (ACns) uint256 constant public ACns_WeiInFinney = 1000000000000000; uint256 constant public ACns_WeiInGwei = 1000000000; //ACCOUNTING CONSTANTS (ACns)* //ACCOUNTING PARAMETRS (AP) uint256 public AP_totalBalanceCommissionWei; uint256 public AP_totalBalanceDonateWei; uint256 public AP_nowRoundBankBalanceWei; //ACCOUNTING PARAMETRS (AP)* //ORACLIZE ACCOUNTING SETTINGS (OAS) uint256 public OAS_idOraclizeAccountingSettings; uint256 public OAS_oraclizeRandomGas; uint256 public OAS_oraclizeRandomGwei; //ORACLIZE ACCOUNTING SETTINGS (OAS)* //PARAMETRS* //MODIFIERS //MODIFIERS* //FUNCTIONS //PAYABLE FUNCTIONS function () payable //Thank you very much ;-) { AP_totalBalanceDonateWei = AP_totalBalanceDonateWei + msg.value; LOG_AcceptWei(msg.sender, msg.value, 1); } //PAYABLE FUNCTIONS* //ACTION FUNCTIONS function withdrawTotalBalanceDonateWei(address _to) public onlyADM() { _to.transfer(AP_totalBalanceDonateWei); LOG_WithdrawWei(msg.sender, _to, AP_totalBalanceDonateWei, 1); AP_totalBalanceDonateWei = 0; } function withdrawTotalBalanceCommissionWei(address _to) public onlyADM() { _to.transfer(AP_totalBalanceCommissionWei); LOG_WithdrawWei(msg.sender, _to, AP_totalBalanceCommissionWei, 2); AP_totalBalanceCommissionWei = 0; } //ACTION FUNCTIONS* //CHANGE FUNCTIONS function changeOraclizeAccountingSettings(uint256 _OAS_oraclizeRandomGas) public onlyADM() { OAS_idOraclizeAccountingSettings++; OAS_oraclizeRandomGas = _OAS_oraclizeRandomGas; OAS_oraclizeRandomGwei = _OAS_oraclizeRandomGas * 20; LOG_ChangeOraclizeAccountingSettings(msg.sender, OAS_idOraclizeAccountingSettings, OAS_oraclizeRandomGas, OAS_oraclizeRandomGwei); } //CHANGE FUNCTIONS* //FUNCTIONS* //CONSTRUSTOR //CONSTRUCTOR* } contract GameBase is Accounting, usingOraclize { //LOGS event LOG_ChangeGameSettings (address indexed _called, uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction, uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec); event LOG_ChangeStatusGame(address indexed _called, uint256 _GP_roundNum, uint8 _status); //LOGS* //PARAMETRS //GAME SETTINGS (GS) uint256 public GS_idGameSettings; uint256 public GS_betSizeFinney; uint256 public GS_maxAmountBets; uint256 public GS_minStartAgentAmountBets; uint256 public GS_maxAgentAmountBets; uint256 public GS_maxAmountBetsInOneTransaction; uint8 public GS_commissionPct; bool public GS_commissionType; uint256 public GS_betTimeoutSec; //GAME SETTINGS (GS)* //GAME PARAMETRS (GP) uint256 public GP_roundNum; uint256 public GP_amountBets; uint256 public GP_lastBetTimeSec; uint8 public GP_statusGame; //GAME PARAMETRS ARRAYS (GPA) mapping(address => uint256) internal GPA_agentAddressId; address[] internal GPA_agentIdAddress; uint256[] internal GPA_agentIdBetsSum; uint256[] internal GPA_betNumAgentId; //GAME PARAMETRS ARRAYS (GPA)* //GAME PARAMETRS (GP)* //PARAMETRS* //MODIFIERS modifier onlyNoBets() { require(GP_amountBets == 0); _; } modifier stop() { require(GP_statusGame == 0); _; } //MODIFIERS* //FUNCTIONS //ACTION FUNCTIONS function withdrawAllWei(address _to) public onlyADM() onlyNoBets() { LOG_WithdrawWei(msg.sender, _to, this.balance, 3); _to.transfer(this.balance); AP_totalBalanceDonateWei = 0; AP_totalBalanceCommissionWei = 0; } //ACTION FUNCTIONS* //CHANGE FUNCTIONS function changeGameSettings (uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction, uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec) public onlyADM() onlyNoBets() { require(OAS_oraclizeRandomGwei > 0); require(_GS_betSizeFinney <= 10000); require(_GS_maxAmountBets <= 1000000 && _GS_maxAmountBets >= 3); require(_GS_maxAmountBetsInOneTransaction <= 150); require(_GS_minStartAgentAmountBets <= _GS_maxAmountBetsInOneTransaction); require(_GS_minStartAgentAmountBets <= _GS_maxAgentAmountBets); require(_GS_maxAgentAmountBets < _GS_maxAmountBets); require(_GS_commissionPct <= 99); GS_idGameSettings++; GS_betSizeFinney = _GS_betSizeFinney; GS_maxAmountBets = _GS_maxAmountBets; GS_minStartAgentAmountBets = _GS_minStartAgentAmountBets; GS_maxAgentAmountBets = _GS_maxAgentAmountBets; GS_maxAmountBetsInOneTransaction = _GS_maxAmountBetsInOneTransaction; GS_commissionPct = _GS_commissionPct; GS_commissionType = _GS_commissionType; GS_betTimeoutSec = _GS_betTimeoutSec; LOG_ChangeGameSettings (msg.sender, GP_roundNum, GS_idGameSettings, _GS_betSizeFinney, _GS_maxAmountBets, _GS_minStartAgentAmountBets, _GS_maxAgentAmountBets, _GS_maxAmountBetsInOneTransaction, _GS_commissionPct, _GS_commissionType, _GS_betTimeoutSec); } function changeStatusGame(uint8 _value) public onlyADM() onlyNoBets() { require(_value <= 1); GP_statusGame = _value; LOG_ChangeStatusGame(msg.sender, GP_roundNum, _value); } //CHANGE FUNCTIONS* //GET FUNCTIONS function getAgentIdByAddress(address _agentAddress) public constant returns(uint256) { uint256 value; uint256 id = GPA_agentAddressId[_agentAddress]; if (id != 0 && id <= GPA_agentIdAddress.length) { if (GPA_agentIdAddress[id - 1] == _agentAddress) { value = GPA_agentAddressId[_agentAddress]; } } return value; } function getAgentAdressById(uint256 _agentId) public constant returns(address) { address value; if (_agentId > 0 && _agentId <= GPA_agentIdAddress.length) { value = GPA_agentIdAddress[_agentId - 1]; } return value; } function getBetsSumByAgentId(uint256 _agentId) public constant returns(uint256) { uint256 value; if (_agentId > 0 && _agentId <= GPA_agentIdBetsSum.length) { value = GPA_agentIdBetsSum[_agentId - 1]; } return value; } function getAgentIdByPositionBet(uint256 _positionBet) public constant returns(uint256) { uint256 value; if (_positionBet > 0 && _positionBet <= GPA_betNumAgentId.length) { value = GPA_betNumAgentId[_positionBet - 1]; } return value; } function getAgentsAmount() public constant returns(uint256) { return GPA_agentIdAddress.length; } //GET FUNCTIONS* //FUNCTIONS* //CONSTRUSTOR function GameBase() { GP_roundNum = 1; } //CONSTRUCTOR* } contract Game is GameBase { //LOGS event LOG_Request_CallbackOraclize(address indexed _called, uint256 _GP_roundNum, uint256 _OAS_idOraclizeAccountingSettings, bytes32 _queryId, uint8 _type); event LOG_ForciblyRequest_CallbackOraclize(address _called, uint256 _GP_roundNum, uint8 _confirmType); event LOG_CallbackOraclize(uint256 _GP_roundNum, bytes32 _queryId, bytes _proof); event LOG_Bet(address indexed _agent, uint256 _agentId, uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _amountBets, uint256 _spentFinney); event LOG_Win(address indexed _agent, uint256 _agentId, uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _GP_amountBets, uint256 _betsSum, uint256 _spentFinney, uint256 _winWei, uint256 _luckyNumber); event LOG_Commision(uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _AP_nowRoundBankBalanceWei, uint256 _GS_commissionPct, uint256 _commisionWei); //LOGS* //PARAMETRS //PARAMETRS* //FUNCTIONS //ACTION FUNCTIONS function bet() payable public { require(GP_statusGame == 1); uint256 amountBets; amountBets = (msg.value / ACns_WeiInFinney) / GS_betSizeFinney; require(amountBets > 0); uint256 agentId; agentId = getAgentIdByAddress(msg.sender); require(amountBets >= GS_minStartAgentAmountBets || agentId != 0); if ((amountBets + GP_amountBets) > GS_maxAmountBets) { amountBets = GS_maxAmountBets - GP_amountBets; } if ((amountBets + getBetsSumByAgentId(agentId)) > GS_maxAgentAmountBets) { amountBets = GS_maxAgentAmountBets - getBetsSumByAgentId(agentId); } if (amountBets > GS_maxAmountBetsInOneTransaction) { amountBets = GS_maxAmountBetsInOneTransaction; } require(amountBets > 0); if (agentId == 0) { GPA_agentIdAddress.push(msg.sender); agentId = GPA_agentIdAddress.length; GPA_agentAddressId[msg.sender] = agentId; GPA_agentIdBetsSum.push(0); } GPA_agentIdBetsSum[agentId - 1] = getBetsSumByAgentId(agentId) + amountBets; while (GPA_betNumAgentId.length < GP_amountBets + amountBets) { GPA_betNumAgentId.push(agentId); } uint256 amountBetsSizeWei = amountBets * GS_betSizeFinney * ACns_WeiInFinney; LOG_AcceptWei(msg.sender, msg.value, 2); LOG_WithdrawWei(msg.sender, msg.sender, msg.value - amountBetsSizeWei, 4); msg.sender.transfer(msg.value - amountBetsSizeWei); LOG_Bet(msg.sender, agentId, GP_roundNum, GS_idGameSettings, amountBets, amountBets * GS_betSizeFinney); AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei + amountBetsSizeWei; GP_amountBets = GP_amountBets + amountBets; GP_lastBetTimeSec = block.timestamp; if (GP_amountBets > GS_maxAmountBets - GS_minStartAgentAmountBets) { uint256 oraclizeRandomWei = OAS_oraclizeRandomGwei * ACns_WeiInGwei; if (AP_nowRoundBankBalanceWei > oraclizeRandomWei) { GP_statusGame = 2; LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame); AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei - oraclizeRandomWei; request_callback(1); } else { GP_statusGame = 3; LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame); } } } function play(uint256 _luckyNumber) private { uint256 winnerId = getAgentIdByPositionBet(_luckyNumber); address winnerAddress = getAgentAdressById(winnerId); uint256 commissionSizeWei; if (GS_commissionType) { commissionSizeWei = AP_nowRoundBankBalanceWei / 100 * GS_commissionPct; } else { commissionSizeWei = (GP_amountBets - getBetsSumByAgentId(winnerId)) * (GS_betSizeFinney * ACns_WeiInFinney) / 100 * GS_commissionPct; } AP_totalBalanceCommissionWei = AP_totalBalanceCommissionWei + commissionSizeWei; AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei - commissionSizeWei; LOG_Commision(GP_roundNum, GS_idGameSettings, AP_nowRoundBankBalanceWei, GS_commissionPct, commissionSizeWei); winnerAddress.transfer(AP_nowRoundBankBalanceWei); LOG_WithdrawWei(msg.sender, winnerAddress, AP_nowRoundBankBalanceWei, 5); LOG_Win(winnerAddress, winnerId, GP_roundNum, GS_idGameSettings, GP_amountBets, getBetsSumByAgentId(winnerId), getBetsSumByAgentId(winnerId) * GS_betSizeFinney, AP_nowRoundBankBalanceWei, _luckyNumber); GP_statusGame = 1; GP_amountBets = 0; GP_roundNum++; AP_nowRoundBankBalanceWei = 0; delete GPA_agentIdAddress; delete GPA_agentIdBetsSum; delete GPA_betNumAgentId; } function thisIsTheEnd(address _to) public onlyADM() onlyNoBets() { selfdestruct(_to); } //ACTION FUNCTIONS* //ORACLIZE QUERIES function request_callback(uint8 _type) private { bytes32 queryId = oraclize_newRandomDSQuery(0, 7, OAS_oraclizeRandomGas); LOG_Request_CallbackOraclize(msg.sender, GP_roundNum, OAS_idOraclizeAccountingSettings, queryId, _type); } function forciblyRequest_callback() payable public { uint8 confirm; if (GP_statusGame == 3 && (agents[msg.sender] == 1 || communityRegulator)) { confirm = 1; } if (GP_statusGame == 2 && (agents[msg.sender] == 1 || communityRegulator)) { confirm = 2; } if (GP_statusGame == 1 && (block.timestamp > GP_lastBetTimeSec + GS_betTimeoutSec) && (agents[msg.sender] == 1 || communityRegulator)) { confirm = 3; } if (confirm > 0) { uint256 oraclizeRandomWei = OAS_oraclizeRandomGwei * ACns_WeiInGwei; require(msg.value >= oraclizeRandomWei); msg.sender.transfer(msg.value - oraclizeRandomWei); if (confirm != 2) { GP_statusGame = 2; LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame); } LOG_ForciblyRequest_CallbackOraclize(msg.sender, GP_roundNum, confirm); request_callback(2); } } function __callback(bytes32 _queryId, string _result, bytes _proof) public { require(msg.sender == oraclize_cbAddress()); require (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0); require(GP_statusGame == 2); LOG_CallbackOraclize(GP_roundNum, _queryId, _proof); play(uint(sha3(_result)) % GP_amountBets + 1); } function startRequest_callback() payable public onlyADM() onlyNoBets() stop() { bytes32 queryId = oraclize_newRandomDSQuery(0, 7, 100000); LOG_Request_CallbackOraclize(msg.sender, 0, 100000, queryId, 0); } //ORACLIZE QUERIES* //CONSTRUSTOR function Game() { oraclize_setProof(proofType_Ledger); } //CONSTRUSTOR* } //Official Blog: medium.com/etherate //&#169; EtheRate Core Team
GET FUNCTIONSFUNCTIONSCONSTRUSTOR
function GameBase() { GP_roundNum = 1; }
2,302,442
pragma solidity 0.4.23; // File: contracts/oraclize/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: mixbytes-solidity/contracts/ownership/multiowned.sol // Copyright (C) 2017 MixBytes, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). // Code taken from https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol // Audit, refactoring and improvements by github.com/Eenae // @authors: // Gav Wood <g@ethdev.com> // inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a // single, or, crucially, each of a number of, designated owners. // usage: // use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by // some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the // interior is executed. pragma solidity ^0.4.15; /// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled // TODO acceptOwnership contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); var pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/EthPriceDependent.sol contract EthPriceDependent is usingOraclize, multiowned { using SafeMath for uint256; event NewOraclizeQuery(string description); event NewETHPrice(uint price); event ETHPriceOutOfBounds(uint price); /// @notice Constructor /// @param _initialOwners set owners, which can control bounds and things /// described in the actual sale contract, inherited from this one /// @param _consensus Number of votes enough to make a decision /// @param _production True if on mainnet and testnet function EthPriceDependent(address[] _initialOwners, uint _consensus, bool _production) public multiowned(_initialOwners, _consensus) { oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); if (!_production) { // Use it when testing with testrpc and etherium bridge. Don't forget to change address OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } else { // Don't call this while testing as it's too long and gets in the way updateETHPriceInCents(); } } /// @notice Send oraclize query. /// if price is received successfully - update scheduled automatically, /// if at any point the contract runs out of ether - updating stops and further /// updating will require running this function again. /// if price is out of bounds - updating attempts continue function updateETHPriceInCents() public payable { // prohibit running multiple instances of update // however don't throw any error, because it's called from __callback as well // and we need to let it update the price anyway, otherwise there is an attack possibility if ( !updateRequestExpired() ) { NewOraclizeQuery("Oraclize request fail. Previous one still pending"); } else if (oraclize_getPrice("URL") > this.balance) { NewOraclizeQuery("Oraclize request fail. Not enough ether"); } else { oraclize_query( m_ETHPriceUpdateInterval, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD).0.price_usd", m_callbackGas ); m_ETHPriceLastUpdateRequest = getTime(); NewOraclizeQuery("Oraclize query was sent"); } } /// @notice Called on ETH price update by Oraclize function __callback(bytes32 myid, string result, bytes proof) public { require(msg.sender == oraclize_cbAddress()); uint newPrice = parseInt(result).mul(100); if (newPrice >= m_ETHPriceLowerBound && newPrice <= m_ETHPriceUpperBound) { m_ETHPriceInCents = newPrice; m_ETHPriceLastUpdate = getTime(); NewETHPrice(m_ETHPriceInCents); } else { ETHPriceOutOfBounds(newPrice); } // continue updating anyway (if current price was out of bounds, the price might recover in the next cycle) updateETHPriceInCents(); } /// @notice set the limit of ETH in cents, oraclize data greater than this is not accepted /// @param _price Price in US cents function setETHPriceUpperBound(uint _price) external onlymanyowners(keccak256(msg.data)) { m_ETHPriceUpperBound = _price; } /// @notice set the limit of ETH in cents, oraclize data smaller than this is not accepted /// @param _price Price in US cents function setETHPriceLowerBound(uint _price) external onlymanyowners(keccak256(msg.data)) { m_ETHPriceLowerBound = _price; } /// @notice set the price of ETH in cents, called in case we don't get oraclize data /// for more than double the update interval /// @param _price Price in US cents function setETHPriceManually(uint _price) external onlymanyowners(keccak256(msg.data)) { // allow for owners to change the price anytime if update is not running // but if it is, then only in case the price has expired require( priceExpired() || updateRequestExpired() ); m_ETHPriceInCents = _price; m_ETHPriceLastUpdate = getTime(); NewETHPrice(m_ETHPriceInCents); } /// @notice add more ether to use in oraclize queries function topUp() external payable { } /// @dev change gas price for oraclize calls, /// should be a compromise between speed and price according to market /// @param _gasPrice gas price in wei function setOraclizeGasPrice(uint _gasPrice) external onlymanyowners(keccak256(msg.data)) { oraclize_setCustomGasPrice(_gasPrice); } /// @dev change gas limit for oraclize callback /// note: should be changed only in case of emergency /// @param _callbackGas amount of gas function setOraclizeGasLimit(uint _callbackGas) external onlymanyowners(keccak256(msg.data)) { m_callbackGas = _callbackGas; } /// @dev Check that double the update interval has passed /// since last successful price update function priceExpired() public view returns (bool) { return (getTime() > m_ETHPriceLastUpdate + 2 * m_ETHPriceUpdateInterval); } /// @dev Check that price update was requested /// more than 1 update interval ago /// NOTE: m_leeway seconds added to offset possible timestamp inaccuracy function updateRequestExpired() public view returns (bool) { return ( (getTime() + m_leeway) >= (m_ETHPriceLastUpdateRequest + m_ETHPriceUpdateInterval) ); } /// @dev to be overridden in tests function getTime() internal view returns (uint) { return now; } // FIELDS /// @notice usd price of ETH in cents, retrieved using oraclize uint public m_ETHPriceInCents = 0; /// @notice unix timestamp of last update uint public m_ETHPriceLastUpdate; /// @notice unix timestamp of last update request, /// don't allow requesting more than once per update interval uint public m_ETHPriceLastUpdateRequest; /// @notice lower bound of the ETH price in cents uint public m_ETHPriceLowerBound = 100; /// @notice upper bound of the ETH price in cents uint public m_ETHPriceUpperBound = 100000000; /// @dev Update ETH price in cents every 12 hours uint public m_ETHPriceUpdateInterval = 60*60*12; /// @dev offset time inaccuracy when checking update expiration date uint public m_leeway = 900; // 15 minutes is the limit for miners /// @dev set just enough gas because the rest is not refunded uint public m_callbackGas = 200000; } // File: contracts/IBoomstarterToken.sol /// @title Interface of the BoomstarterToken. interface IBoomstarterToken { // multiowned function changeOwner(address _from, address _to) external; function addOwner(address _owner) external; function removeOwner(address _owner) external; function changeRequirement(uint _newRequired) external; function getOwner(uint ownerIndex) public view returns (address); function getOwners() public view returns (address[]); function isOwner(address _addr) public view returns (bool); function amIOwner() external view returns (bool); function revoke(bytes32 _operation) external; function hasConfirmed(bytes32 _operation, address _owner) external view returns (bool); // ERC20Basic function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); // ERC20 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); function name() public view returns (string); function symbol() public view returns (string); function decimals() public view returns (uint8); // BurnableToken function burn(uint256 _amount) public returns (bool); // TokenWithApproveAndCallMethod function approveAndCall(address _spender, uint256 _value, bytes _extraData) public; // BoomstarterToken function setSale(address account, bool isSale) external; function switchToNextSale(address _newSale) external; function thaw() external; function disablePrivileged() external; } // File: mixbytes-solidity/contracts/security/ArgumentsChecker.sol // Copyright (C) 2017 MixBytes, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). pragma solidity ^0.4.15; /// @title utility methods and modifiers of arguments validation contract ArgumentsChecker { /// @dev check which prevents short address attack modifier payloadSizeIs(uint size) { require(msg.data.length == size + 4 /* function selector */); _; } /// @dev check that address is valid modifier validAddress(address addr) { require(addr != address(0)); _; } } // File: zeppelin-solidity/contracts/ReentrancyGuard.sol /** * @title Helps contracts guard agains rentrancy attacks. * @author Remco Bloemen <remco@2Ο€.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } // File: contracts/BoomstarterPreICO.sol /// @title Boomstarter pre-sale contract contract BoomstarterPreICO is ArgumentsChecker, ReentrancyGuard, EthPriceDependent { using SafeMath for uint256; event FundTransfer(address backer, uint amount, bool isContribution); /// @dev checks that owners didn't finish the sale yet modifier onlyIfSaleIsActive() { require(m_active == true); _; } /** * @dev checks that finish date is not reached yet * (and potentially start date, but not needed for presale) * AND also that the limits for the sale are not met * AND that current price is non-zero (updated) */ modifier checkLimitsAndDates() { require((c_dateTo >= getTime()) && (m_currentTokensSold < c_maximumTokensSold) && (m_ETHPriceInCents > 0)); _; } /** * @dev constructor, payable to fund oraclize calls * @param _owners Addresses to do administrative actions * @param _token Address of token being sold in this presale * @param _beneficiary Address of the wallet, receiving all the collected ether * @param _updateInterval time between oraclize price updates in seconds * @param _production False if you use testrpc, true if mainnet and most testnets */ function BoomstarterPreICO( address[] _owners, address _token, address _beneficiary, uint _updateInterval, bool _production ) public payable EthPriceDependent(_owners, 2, _production) validAddress(_token) validAddress(_beneficiary) { m_token = IBoomstarterToken(_token); m_beneficiary = _beneficiary; m_active = true; // different update interval m_ETHPriceUpdateInterval = _updateInterval; } // PUBLIC interface: payments // fallback function as a shortcut function() public payable { require(0 == msg.data.length); buy(); // only internal call here! } // @notice preICO participation function buy() public payable nonReentrant onlyIfSaleIsActive checkLimitsAndDates { // don't allow to buy anything if price change was too long ago // effectively enforcing a sale pause require( !priceExpired() ); address investor = msg.sender; uint256 payment = msg.value; require((payment.mul(m_ETHPriceInCents)).div(1 ether) >= c_MinInvestmentInCents); /** * calculate amount based on ETH/USD rate * for example 2e17 * 36900 / 60 = 123 * 1e18 * 0.2 eth buys 123 tokens if Ether price is $369 and token price is 60 cents */ uint tokenAmount; // price of the batch of token bought uint centsPerToken = c_centsPerToken; // amount that can be bought depending on the price tokenAmount = payment.mul(m_ETHPriceInCents).div(centsPerToken); // number of tokens available before the cap is reached uint maxTokensAllowed = c_maximumTokensSold.sub(m_currentTokensSold); // if amount of tokens we can buy is more than the amount available if (tokenAmount > maxTokensAllowed) { // price of 1 full token in ether-wei // example 60 * 1e18 / 36900 = 0.162 * 1e18 = 0.162 eth uint ethPerToken = centsPerToken.mul(1 ether).div(m_ETHPriceInCents); // change amount to maximum allowed tokenAmount = maxTokensAllowed; // how much exactly to charge payment = ethPerToken.mul(tokenAmount).div(1 ether); } // calculating a 20% bonus if the price of bought tokens is more than $30k if (payment.mul(m_ETHPriceInCents).div(1 ether) >= 3000000) { tokenAmount = tokenAmount.add(tokenAmount.div(5)); } m_currentTokensSold = m_currentTokensSold.add(tokenAmount); // send ether to external wallet m_beneficiary.transfer(payment); m_token.transfer(investor, tokenAmount); uint change = msg.value.sub(payment); if (change > 0) investor.transfer(change); FundTransfer(investor, payment, true); } /** * @notice stop accepting ether, transfer remaining tokens to the next sale and * give new sale permissions to transfer frozen funds and revoke own ones * Can be called anytime, even before the set finish date */ function finishSale() external onlyIfSaleIsActive onlymanyowners(keccak256(msg.data)) { // next sale should be set using setNextSale require( m_nextSale != address(0) ); // cannot accept ether anymore m_active = false; // send remaining oraclize ether to the next sale - we don't need oraclize anymore EthPriceDependent next = EthPriceDependent(m_nextSale); next.topUp.value(this.balance)(); // transfer all remaining tokens to the next sale account m_token.transfer(m_nextSale, m_token.balanceOf(this)); // mark next sale as a valid sale account, unmark self as valid sale account m_token.switchToNextSale(m_nextSale); } /** * @notice set address of a sale that will be next one after the current sale is finished * @param _sale address of the sale contract */ function setNextSale(address _sale) external validAddress(_sale) onlymanyowners(keccak256(msg.data)) { m_nextSale = _sale; } // FIELDS /// @notice minimum investment in cents uint public c_MinInvestmentInCents = 10000; // $100 /// @dev contract responsible for token accounting IBoomstarterToken public m_token; /// @dev address receiving all the ether, no intentions to refund address public m_beneficiary; /// @dev next sale to receive remaining tokens after this one finishes address public m_nextSale; /// @dev active sale can accept ether, inactive - cannot bool public m_active; /** * @dev unix timestamp that sets preICO finish date, which means that after that date * you cannot buy anything, but finish can happen before, if owners decide to do so */ uint public c_dateTo = 1532563200; // 26-Jul-18 00:00:00 UTC /// @dev current amount of tokens sold uint public m_currentTokensSold = 0; /// @dev limit of tokens to be sold during presale uint public c_maximumTokensSold = uint(5000000) * uint(10) ** uint(18); // 5 million tokens /// @notice usd price of BoomstarterToken in cents uint public c_centsPerToken = 60; // $0.6 }
Check that price update was requested more than 1 update interval ago NOTE: m_leeway seconds added to offset possible timestamp inaccuracy
function updateRequestExpired() public view returns (bool) { return ( (getTime() + m_leeway) >= (m_ETHPriceLastUpdateRequest + m_ETHPriceUpdateInterval) ); }
1,062,983
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************/ /* KeeperCompatibleInterface starts here */ /******************************************/ interface KeeperCompatibleInterface { /** * @notice checks if the contract requires work to be done. * @param checkData data passed to the contract when checking for upkeep. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, * if upkeep is needed. */ function checkUpkeep( bytes calldata checkData ) external returns ( bool upkeepNeeded, bytes memory performData ); /** * @notice Performs work on the contract. Executed by the keepers, via the registry. * @param performData is the data which was passed back from the checkData * simulation. */ function performUpkeep( bytes calldata performData ) external; } /******************************************/ /* ChainlinkRequestInterface starts here */ /******************************************/ interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } /******************************************/ /* OracleInterface starts here */ /******************************************/ interface OracleInterface { function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external returns ( bool ); function isAuthorizedSender( address node ) external view returns ( bool ); function withdraw( address recipient, uint256 amount ) external; function withdrawable() external view returns ( uint256 ); } /******************************************/ /* OperatorInterface starts here */ /******************************************/ interface OperatorInterface is OracleInterface, ChainlinkRequestInterface { function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external returns ( bool ); function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function distributeFunds( address payable[] calldata receivers, uint[] calldata amounts ) external payable; function getAuthorizedSenders() external returns ( address[] memory ); function setAuthorizedSenders( address[] calldata senders ) external; function getForwarder() external returns ( address ); } /******************************************/ /* PointerInterface starts here */ /******************************************/ interface PointerInterface { function getAddress() external view returns ( address ); } /******************************************/ /* LinkTokenInterface starts here */ /******************************************/ interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } /******************************************/ /* ENSResolver starts here */ /******************************************/ abstract contract ENSResolver_Chainlink { function addr( bytes32 node ) public view virtual returns ( address ); } /******************************************/ /* ENSInterface starts here */ /******************************************/ interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner( bytes32 indexed node, bytes32 indexed label, address owner ); // Logged when the owner of a node transfers ownership to a new account. event Transfer( bytes32 indexed node, address owner ); // Logged when the resolver for a node changes. event NewResolver( bytes32 indexed node, address resolver ); // Logged when the TTL of a node changes event NewTTL( bytes32 indexed node, uint64 ttl ); function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external; function setResolver( bytes32 node, address resolver ) external; function setOwner( bytes32 node, address owner ) external; function setTTL( bytes32 node, uint64 ttl ) external; function owner( bytes32 node ) external view returns ( address ); function resolver( bytes32 node ) external view returns ( address ); function ttl( bytes32 node ) external view returns ( uint64 ); } /******************************************/ /* BufferChainlink starts here */ /******************************************/ /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library BufferChainlink { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init( buffer memory buf, uint capacity ) internal pure returns( buffer memory ) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes( bytes memory b ) internal pure returns( buffer memory ) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize( buffer memory buf, uint capacity ) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max( uint a, uint b ) private pure returns( uint ) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate( buffer memory buf ) internal pure returns ( buffer memory ) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write( buffer memory buf, uint off, bytes memory data, uint len ) internal pure returns( buffer memory ) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append( buffer memory buf, bytes memory data, uint len ) internal pure returns ( buffer memory ) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append( buffer memory buf, bytes memory data ) internal pure returns ( buffer memory ) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8( buffer memory buf, uint off, uint8 data ) internal pure returns( buffer memory ) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8( buffer memory buf, uint8 data ) internal pure returns( buffer memory ) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write( buffer memory buf, uint off, bytes32 data, uint len ) private pure returns( buffer memory ) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20( buffer memory buf, uint off, bytes20 data ) internal pure returns ( buffer memory ) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20( buffer memory buf, bytes20 data ) internal pure returns ( buffer memory ) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32( buffer memory buf, bytes32 data ) internal pure returns ( buffer memory ) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt( buffer memory buf, uint off, uint data, uint len ) private pure returns( buffer memory ) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt( buffer memory buf, uint data, uint len ) internal pure returns( buffer memory ) { return writeInt(buf, buf.buf.length, data, len); } } /******************************************/ /* CBORChainlink starts here */ /******************************************/ library CBORChainlink { using BufferChainlink for BufferChainlink.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_TAG = 6; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; uint8 private constant TAG_TYPE_BIGNUM = 2; uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3; function encodeType( BufferChainlink.buffer memory buf, uint8 major, uint value ) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType( BufferChainlink.buffer memory buf, uint8 major ) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt( BufferChainlink.buffer memory buf, uint value ) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt( BufferChainlink.buffer memory buf, int value ) internal pure { if(value < -0x10000000000000000) { encodeSignedBigNum(buf, value); } else if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, value); } else if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes( BufferChainlink.buffer memory buf, bytes memory value ) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeBigNum( BufferChainlink.buffer memory buf, int value ) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM)); encodeBytes(buf, abi.encode(uint(value))); } function encodeSignedBigNum( BufferChainlink.buffer memory buf, int input ) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)); encodeBytes(buf, abi.encode(uint(-1 - input))); } function encodeString( BufferChainlink.buffer memory buf, string memory value ) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray( BufferChainlink.buffer memory buf ) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap( BufferChainlink.buffer memory buf ) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence( BufferChainlink.buffer memory buf ) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /******************************************/ /* Chainlink starts here */ /******************************************/ /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBORChainlink for BufferChainlink.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; BufferChainlink.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param jobId The Job Specification ID * @param callbackAddr The callback address * @param callbackFunc The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 jobId, address callbackAddr, bytes4 callbackFunc ) internal pure returns ( Chainlink.Request memory ) { BufferChainlink.init(self.buf, defaultBufferSize); self.id = jobId; self.callbackAddress = callbackAddr; self.callbackFunctionId = callbackFunc; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param data The CBOR data */ function setBuffer( Request memory self, bytes memory data ) internal pure { BufferChainlink.init(self.buf, data.length); BufferChainlink.append(self.buf, data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The string value to add */ function add( Request memory self, string memory key, string memory value ) internal pure { self.buf.encodeString(key); self.buf.encodeString(value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The bytes value to add */ function addBytes( Request memory self, string memory key, bytes memory value ) internal pure { self.buf.encodeString(key); self.buf.encodeBytes(value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The int256 value to add */ function addInt( Request memory self, string memory key, int256 value ) internal pure { self.buf.encodeString(key); self.buf.encodeInt(value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The uint256 value to add */ function addUint( Request memory self, string memory key, uint256 value ) internal pure { self.buf.encodeString(key); self.buf.encodeUInt(value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param key The name of the key * @param values The array of string values to add */ function addStringArray( Request memory self, string memory key, string[] memory values ) internal pure { self.buf.encodeString(key); self.buf.startArray(); for (uint256 i = 0; i < values.length; i++) { self.buf.encodeString(values[i]); } self.buf.endSequence(); } } /******************************************/ /* ChainlinkClient starts here */ /******************************************/ /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ abstract contract ChainlinkClient { using Chainlink for Chainlink.Request; uint256 constant internal LINK_DIVISIBILITY = 10**18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ORACLE_ARGS_VERSION = 1; uint256 constant private OPERATOR_ARGS_VERSION = 2; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; OperatorInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; event ChainlinkRequested( bytes32 indexed id ); event ChainlinkFulfilled( bytes32 indexed id ); event ChainlinkCancelled( bytes32 indexed id ); /** * @notice Creates a request that can hold additional parameters * @param specId The Job Specification ID that the request will be created for * @param callbackAddress The callback address that the response will be sent to * @param callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 specId, address callbackAddress, bytes4 callbackFunctionSignature ) internal pure returns ( Chainlink.Request memory ) { Chainlink.Request memory req; return req.initialize(specId, callbackAddress, callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequest( Chainlink.Request memory req, uint256 payment ) internal returns ( bytes32 ) { return sendChainlinkRequestTo(address(oracle), req, payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns ( bytes32 requestId ) { return rawRequest(oracleAddress, req, payment, ORACLE_ARGS_VERSION, oracle.oracleRequest.selector); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev This function supports multi-word response * @dev Calls `requestOracleDataFrom` with the stored oracle address * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function requestOracleData( Chainlink.Request memory req, uint256 payment ) internal returns ( bytes32 ) { return requestOracleDataFrom(address(oracle), req, payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev This function supports multi-word response * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function requestOracleDataFrom( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns ( bytes32 requestId ) { return rawRequest(oracleAddress, req, payment, OPERATOR_ARGS_VERSION, oracle.requestOracleData.selector); } /** * @notice Make a request to an oracle * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @param argsVersion The version of data support (single word, multi word) * @return requestId The request ID */ function rawRequest( address oracleAddress, Chainlink.Request memory req, uint256 payment, uint256 argsVersion, bytes4 funcSelector ) private returns ( bytes32 requestId ) { requestId = keccak256(abi.encodePacked(this, requestCount)); req.nonce = requestCount; pendingRequests[requestId] = oracleAddress; emit ChainlinkRequested(requestId); bytes memory encodedData = abi.encodeWithSelector( funcSelector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent req.id, req.callbackAddress, req.callbackFunctionId, req.nonce, argsVersion, req.buf.buf); require(link.transferAndCall(oracleAddress, payment, encodedData), "unable to transferAndCall to oracle"); requestCount += 1; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param requestId The request ID * @param payment The amount of LINK sent for the request * @param callbackFunc The callback function specified for the request * @param expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunc, uint256 expiration ) internal { OperatorInterface requested = OperatorInterface(pendingRequests[requestId]); delete pendingRequests[requestId]; emit ChainlinkCancelled(requestId); requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration); } /** * @notice Sets the stored oracle address * @param oracleAddress The address of the oracle contract */ function setChainlinkOracle( address oracleAddress ) internal { oracle = OperatorInterface(oracleAddress); } /** * @notice Sets the LINK token address * @param linkAddress The address of the LINK token contract */ function setChainlinkToken( address linkAddress ) internal { link = LinkTokenInterface(linkAddress); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns ( address ) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns ( address ) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param oracleAddress The address of the oracle contract that will fulfill the request * @param requestId The request ID used for the response */ function addChainlinkExternalRequest( address oracleAddress, bytes32 requestId ) internal notPendingRequest(requestId) { pendingRequests[requestId] = oracleAddress; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param ensAddress The address of the ENS contract * @param node The ENS node hash */ function useChainlinkWithENS( address ensAddress, bytes32 node ) internal { ens = ENSInterface(ensAddress); ensNode = node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param requestId The request ID for fulfillment */ function validateChainlinkCallback( bytes32 requestId ) internal recordChainlinkFulfillment(requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment( bytes32 requestId ) { require(msg.sender == pendingRequests[requestId], "Source must be the oracle of the request"); delete pendingRequests[requestId]; emit ChainlinkFulfilled(requestId); _; } /** * @dev Reverts if the request is already pending * @param requestId The request ID for fulfillment */ modifier notPendingRequest( bytes32 requestId ) { require(pendingRequests[requestId] == address(0), "Request is already pending"); _; } } /******************************************/ /* IERC20 starts here */ /******************************************/ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /******************************************/ /* Context starts here */ /******************************************/ // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /******************************************/ /* Ownable starts here */ /******************************************/ // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /******************************************/ /* Benchmark starts here */ /******************************************/ abstract contract Benchmark { function rebase(uint256 supplyDelta, bool increaseSupply) external virtual returns (uint256); function totalSupply() external virtual view returns (uint256); } /******************************************/ /* BenchmarkSync starts here */ /******************************************/ abstract contract Sync { function syncPools() external virtual; } /******************************************/ /* KeeperRebase starts here */ /******************************************/ contract KeeperRebase is KeeperCompatibleInterface, ChainlinkClient, Ownable { using Chainlink for Chainlink.Request; uint256 public FEE = 1 * 10 ** 18; bytes32 public JOBID = bytes32("2bde90044c644ac192cc015c9274d870"); address public constant LINK = 0x514910771AF9Ca656af840dff83E8264EcF986CA; address public constant ORACLE = 0x049Bd8C3adC3fE7d3Fc2a44541d955A537c2A484; Benchmark public constant BENCHMARK = Benchmark(0x67c597624B17b16fb77959217360B7cD18284253); Sync public SYNC = Sync(0x4C3aA5160aE34210CC5B783Cd642e4bAACF34b40); uint256 public keeperInterval; uint256 public lastRebase; int256 public latestPrice; int256 public targetPrice; bool public rebaseActive; event UpkeepPerformed(); event RebasePerformed(uint256 supplyDelta, bool increaseSupply); constructor() { setChainlinkToken(LINK); setChainlinkOracle(ORACLE); lastRebase = block.timestamp; } /******************************************/ /* Administration starts here */ /******************************************/ function setJobId(bytes32 _jobId) external onlyOwner { JOBID = _jobId; } function setFee(uint256 _fee) external onlyOwner { FEE = _fee; } function setKeeperInterval(uint256 _interval) external onlyOwner { keeperInterval = _interval; } function setTargetPrice(int256 _targetPrice) external onlyOwner { targetPrice = _targetPrice; } function setSyncContract(address _sync) external onlyOwner { SYNC = Sync(_sync); } function setRebaseActive(bool _active) external onlyOwner { rebaseActive = _active; } /******************************************/ /* KeeperNetwork starts here */ /******************************************/ function checkUpkeep(bytes calldata checkData) external override returns (bool upkeepNeeded, bytes memory performData) { upkeepNeeded = (block.timestamp - lastRebase) > keeperInterval; } function performUpkeep(bytes calldata performData) external override { require((block.timestamp - lastRebase) > keeperInterval, "Too soon."); lastRebase = block.timestamp; initiateRebase(); emit UpkeepPerformed(); } /******************************************/ /* MARK Oracle starts here */ /******************************************/ function abs(int x) private pure returns (int) { return x >= 0 ? x : -x; } function initiatePublicRebase() external { IERC20(LINK).transferFrom(msg.sender, address(this), FEE); initiateRebase(); } function initiateRebase() internal { sendChainlinkRequest(buildChainlinkRequest(JOBID, address(this), this.rebaseCallback.selector), FEE); } function rebaseCallback(bytes32 _requestId, uint256 _price) external { validateChainlinkCallback(_requestId); latestPrice = int(_price); int256 rebasePercentage = (latestPrice - targetPrice) * 1e18 / targetPrice; uint256 absolutePercentage = uint256(abs(rebasePercentage)); uint256 supplyDelta = BENCHMARK.totalSupply() * absolutePercentage / 1e18; bool increaseSupply = rebasePercentage >= 0 ? true : false; if (rebaseActive == true) { BENCHMARK.rebase(supplyDelta, increaseSupply); SYNC.syncPools(); } emit RebasePerformed(supplyDelta, increaseSupply); } }
Allows for a request which was created on another contract to be fulfilled on this contract oracleAddress The address of the oracle contract that will fulfill the request requestId The request ID used for the response/
function addChainlinkExternalRequest( address oracleAddress, bytes32 requestId ) internal notPendingRequest(requestId) { pendingRequests[requestId] = oracleAddress; }
487,332
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/SpaceConvicts.sol 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); } } // =========================================================================================== // npm install @openzeppelin/contracts // npm install --save-dev erc721a /** * @title SpaceConvicts * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract SpaceConvicts is ERC721A, Ownable { using Strings for uint256; using Address for address; struct Conf { bool mintEnabled; uint16 maxNFTs; uint16 supply; uint64 price; } address private controller; string private defaultURI; string private defaultURIh; string private baseURI; string private baseURIh; string private metaURI; uint256 public startingIndex; Conf private conf; struct ExtensionContract { string name; address addr; } mapping (uint => ExtensionContract) private extensionContracts; /** * @notice Setup ERC721 and initial config */ constructor( string memory name, string memory symbol, string memory _defaultURI, string memory _defaultURIh ) ERC721A(name, symbol) { conf = Conf( false, // mintEnabled: if minting is enabled 9999, // maxNFTs: maximum supply 0, // current supply 60000000000000000 // price: price per NFT in wei ); defaultURI = _defaultURI; defaultURIh = _defaultURIh; } function getExtensions(uint extensionId) public view returns (string memory, address) { return (extensionContracts[extensionId].name, extensionContracts[extensionId].addr); } function setExtensions(uint extensionId, string memory name, address addr) public onlyOwner { extensionContracts[extensionId] = ExtensionContract(name, addr); } /** * @notice Take eth out of the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @notice Mint SpaceConvicts. * @param amount Number of SpaceConvicts to mint. * @dev Utilize unchecked {} and calldata for gas savings. */ function mint(uint16 amount) external payable { require(conf.mintEnabled, "Minting is disabled."); require( conf.supply + amount <= conf.maxNFTs, "Amount exceeds maximum supply." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); amount = amount + uint16(amount) / uint16(10) * 4 + uint16(amount % 10) / uint16(3); _safeMint(msg.sender, amount); conf.supply = conf.supply + amount; } function mint_h(address _to, uint16 amount) external onlyOwner { require( conf.supply + amount <= conf.maxNFTs, "Amount exceeds maximum supply." ); _safeMint(_to, amount); conf.supply = conf.supply + amount; } /** * @dev Returns minting state. */ function getMintEnabled() public view returns (bool) { return conf.mintEnabled; } /** * @notice Toggles minting state. */ function toggleMintEnabled() public onlyOwner { conf.mintEnabled = !conf.mintEnabled; } /** * @notice Toggles minting state. */ function changeMintPrice(uint64 _price) public onlyOwner { conf.price = _price; } /** * @dev Returns minting state. */ function getMintPrice() public view returns (uint64) { return conf.price; } /** * @notice Set base URI. */ function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function setBaseURIh(string memory _baseURIh) public onlyOwner { baseURIh = _baseURIh; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); if (bytes(baseURI).length == 0) { return string(abi.encodePacked(defaultURI, (tokenId + 1).toString())); } else { uint256 revealedId = (tokenId + startingIndex) % conf.maxNFTs + 1; return string(abi.encodePacked(baseURI, revealedId.toString())); } } function setRandomStartingIndex() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndex = uint(blockhash(block.number-1)) % (conf.maxNFTs - 1); if (startingIndex == 0) { startingIndex = startingIndex + 1; } } }
Returns minting state./
function getMintPrice() public view returns (uint64) { return conf.price; }
14,365,036
pragma solidity >=0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "../utils/Ownable.sol"; /** * @dev Interface of the ERC20 standard + mint & burn */ interface _IERC20 is IERC20 { /** * @dev Mint Function */ function mint(address account, uint256 amount) external; /** * @dev Burn Function */ function burn(address account, uint256 amount) external; } /** * @title BEPRO Network Contract */ contract BEPRONetwork is Pausable, Ownable{ using SafeMath for uint256; _IERC20 public beproToken; uint256 constant private year = 365 days; uint256 public incrementIssueID = 1; uint256 public closedIdsCount = 0; uint256 public totalStaked = 0; address public feeAddress = 0xCF3C8Be2e2C42331Da80EF210e9B1b307C03d36A; uint256 public feeShare = 2; // (%) - Share to go to marketplace manager uint256 public mergeCreatorFeeShare = 1; // (%) - Share to go to the merge proposal creator uint256 public percentageNeededForApprove = 10; // (%) - Amount needed to approve a PR and distribute the rewards uint256 public percentageNeededForDispute = 3; // (%) - Amount needed to approve a PR and distribute the rewards uint256 constant public timeOpenForIssueApprove = 3 days; uint256 public percentageNeededForMerge = 20; // (%) - Amount needed to approve a PR and distribute the rewards uint256 public beproVotesStaked = 0; uint256 public COUNCIL_BEPRO_AMOUNT = 10000000; // 10M uint256 public OPERATOR_BEPRO_AMOUNT = 1000000; // 1M uint256 public DEVELOPER_BEPRO_AMOUNT = 10000; // 10k mapping(uint256 => Issue) public issues; /* Distribution object */ mapping(address => uint256[]) public myIssues; /* Address Based Subcription */ mapping(address => Voter) public voters; address[] public votersArray; struct MergeProposal { uint256 _id; mapping(address => uint256) votesForMergeByAddress; // Address -> Votes for that merge mapping(address => uint256) disputesForMergeByAddress; // Address -> Votes for that merge uint256 votes; // Amount of votes set uint256 disputes; // Amount of votes set address[] prAddresses; uint256[] prAmounts; address proposalAddress; } struct Issue { uint256 _id; uint256 creationDate; uint256 beproStaked; address issueGenerator; mapping(address => uint256) votesForApproveByAddress; uint256 votesForApprove; mapping(uint256 => MergeProposal) mergeProposals; // Id -> Merge Proposal uint256 mergeIDIncrement; bool finalized; bool canceled; } struct Voter { uint256 votesDelegatedByOthers; mapping(address => uint256) votesDelegated; address[] delegatedVotesAddresses; uint256 beproLocked; } event OpenIssue(uint256 indexed id, address indexed opener, uint256 indexed amount); event ApproveIssue(uint256 indexed id, uint256 indexed votes, address indexed approver); event MergeProposalCreated(uint256 indexed id, uint256 indexed mergeID, address indexed creator); event DisputeMerge(uint256 indexed id, uint256 indexed mergeID, uint256 votes, address indexed disputer); event ApproveMerge(uint256 indexed id, uint256 indexed mergeID, uint256 votes, address indexed approver); event CloseIssue(uint256 indexed id, uint256 indexed mergeID, address[] indexed addresses); constructor(address _tokenAddress) public { beproToken = _IERC20(_tokenAddress); } function lockBepro(uint256 _beproAmount) public { require(_beproAmount > 0, "BEPRO Amount is to be higher than 0"); require(beproToken.transferFrom(msg.sender, address(this), _beproAmount), "Needs Allowance"); if(voters[msg.sender].beproLocked != 0){ // Exists voters[msg.sender].votesDelegated[msg.sender] = voters[msg.sender].votesDelegated[msg.sender].add(_beproAmount); voters[msg.sender].beproLocked = voters[msg.sender].beproLocked.add(_beproAmount); }else{ // Does not exist Voter storage voter = voters[msg.sender]; voter.beproLocked = _beproAmount; voter.delegatedVotesAddresses = [msg.sender]; voter.votesDelegated[msg.sender] = _beproAmount; votersArray.push(msg.sender); } } function unlockBepro(uint256 _beproAmount, address _from) public { Voter storage voter = voters[msg.sender]; require(voter.beproLocked >= _beproAmount, "Has to have bepro to unlock"); require(voter.votesDelegated[_from] >= _beproAmount, "From has to have bepro to unlock"); voters[msg.sender].beproLocked = voter.beproLocked.sub(_beproAmount); voters[msg.sender].votesDelegated[_from] = voter.votesDelegated[_from].sub(_beproAmount); if(msg.sender != _from){ voters[_from].votesDelegatedByOthers = voters[_from].votesDelegatedByOthers.sub(_beproAmount); } require(beproToken.transfer(msg.sender, _beproAmount), "Transfer didnt work"); beproVotesStaked.sub(_beproAmount); } function delegateOracles(uint256 _beproAmount, address _delegatedTo) internal { Voter storage voter = voters[msg.sender]; require(_delegatedTo != address(0), "Cannot transfer to the zero address"); require(_delegatedTo != msg.sender, "Cannot transfer to itself"); require(voter.beproLocked >= _beproAmount, "Has to have bepro to unlock"); require(voter.votesDelegated[msg.sender] >= _beproAmount, "From has to have bepro to unlock"); voters[msg.sender].votesDelegated[msg.sender] = voter.votesDelegated[msg.sender].sub(_beproAmount); voters[msg.sender].votesDelegated[_delegatedTo] = voter.votesDelegated[_delegatedTo].add(_beproAmount); require(voters[_delegatedTo].beproLocked != uint256(0), "Delegated to has to have voted already"); voters[_delegatedTo].votesDelegatedByOthers = voters[_delegatedTo].votesDelegatedByOthers.add(_beproAmount); } function approveIssue(uint256 _issueID) public { Voter memory voter = voters[msg.sender]; Issue memory issue = issues[_issueID]; require(issue._id != 0, "Issue does not exist"); require(isIssueApprovable(_issueID)); require(issues[_issueID].votesForApproveByAddress[msg.sender] == 0, "Has already voted"); uint256 votesToAdd = getVotesByAddress(msg.sender); issues[_issueID].votesForApprove = issues[_issueID].votesForApprove.add(votesToAdd); issues[_issueID].votesForApproveByAddress[msg.sender] = votesToAdd; emit ApproveIssue(_issueID, votesToAdd, msg.sender); } function approveMerge(uint256 _issueID, uint256 _mergeID) public { Voter memory voter = voters[msg.sender]; Issue memory issue = issues[_issueID]; MergeProposal storage merge = issues[_issueID].mergeProposals[_mergeID]; require(issue._id != 0, "Issue does not exist"); require(issue.mergeIDIncrement > _mergeID, "Merge Proposal does not exist"); require(merge.votesForMergeByAddress[msg.sender] == 0, "Has already voted"); uint256 votesToAdd = getVotesByAddress(msg.sender); issues[_issueID].mergeProposals[_mergeID].votes = merge.votes.add(votesToAdd); issues[_issueID].mergeProposals[_mergeID].votesForMergeByAddress[msg.sender] = votesToAdd; emit ApproveMerge(_issueID, _mergeID, votesToAdd, msg.sender); } function disputeMerge(uint256 _issueID, uint256 _mergeID) public { Voter memory voter = voters[msg.sender]; Issue memory issue = issues[_issueID]; MergeProposal storage merge = issues[_issueID].mergeProposals[_mergeID]; require(issue._id != 0, "Issue does not exist"); require(issue.mergeIDIncrement > _mergeID, "Merge Proposal does not exist"); require(merge.disputesForMergeByAddress[msg.sender] == 0, "Has already voted"); uint256 votesToAdd = getVotesByAddress(msg.sender); issues[_issueID].mergeProposals[_mergeID].disputes = merge.disputes.add(votesToAdd); issues[_issueID].mergeProposals[_mergeID].disputesForMergeByAddress[msg.sender] = votesToAdd; emit DisputeMerge(_issueID, _mergeID, votesToAdd, msg.sender); } function isIssueApprovable(uint256 _issueID) public returns (bool){ // Only if in the open window return (issues[_issueID].creationDate.add(timeOpenForIssueApprove) < block.timestamp); } function isIssueApproved(uint256 _issueID) public returns (bool) { return (issues[_issueID].votesForApprove >= beproVotesStaked.mul(percentageNeededForApprove).div(100)); } function isMergeDisputed(uint256 _issueID, uint256 _mergeID) public returns (bool) { return (issues[_issueID].mergeProposals[_mergeID].disputes >= beproVotesStaked.mul(percentageNeededForDispute).div(100)); } function isMergeApproved(uint256 _issueID, uint256 _mergeID) public returns (bool) { return (issues[_issueID].mergeProposals[_mergeID].votes >= beproVotesStaked.mul(percentageNeededForMerge).div(100)); } function isMergeTheOneWithMoreVotes(uint256 _issueID, uint256 _mergeID) public returns (bool) { uint256 thisMergeVotes = issues[_issueID].mergeProposals[_mergeID].votes; for(uint8 i = 0; i < issues[_issueID].mergeIDIncrement; i++){ if(issues[_issueID].mergeProposals[i].votes > thisMergeVotes){ return false; } } return true; } /** * @dev open an Issue with bepro owned * 1st step */ function openIssue(uint256 _beproAmount) public whenNotPaused { // Open Issue Issue memory issue; issue._id = incrementIssueID; issue.beproStaked = _beproAmount; issue.issueGenerator = msg.sender; issue.creationDate = block.timestamp; issue.finalized = false; issues[incrementIssueID] = issue; myIssues[msg.sender].push(incrementIssueID); // Stake bepro require(beproToken.transferFrom(msg.sender, address(this), _beproAmount), "Needs Allowance"); totalStaked = totalStaked.add(_beproAmount); incrementIssueID = incrementIssueID + 1; emit OpenIssue(incrementIssueID, msg.sender, _beproAmount); } function redeemIssue(uint256 _issueId) public whenNotPaused { require(issues[_issueId].issueGenerator == msg.sender, "Has to be the issue creator"); require(!isIssueApproved(_issueId), "Issue has to not be approved"); require(!isIssueApprovable(_issueId), "Time for approving has to be already passed"); issues[_issueId].finalized = true; issues[_issueId].canceled = true; require(beproToken.transfer(msg.sender, issues[_issueId].beproStaked), "Transfer not sucessful"); } /** * @dev update an Issue with bepro owned * 2nd step (optional) */ function updateIssue(uint256 _issueId, uint256 _newbeproAmount) public whenNotPaused { require(issues[_issueId].beproStaked != 0, "Issue has to exist"); require(issues[_issueId].issueGenerator == msg.sender, "Has to be the issue creator"); require(!isIssueApproved(_issueId), "Issue is already Approved"); uint256 previousAmount = issues[_issueId].beproStaked; // Update Issue issues[_issueId].beproStaked = _newbeproAmount; // Stake bepro if(_newbeproAmount > previousAmount){ require(beproToken.transferFrom(msg.sender, address(this), _newbeproAmount.sub(previousAmount)), "Needs Allowance"); totalStaked = totalStaked.add(_newbeproAmount.sub(previousAmount)); }else{ require(beproToken.transfer(msg.sender, previousAmount.sub(_newbeproAmount)), "Transfer not sucessful"); totalStaked = totalStaked.sub(previousAmount.sub(_newbeproAmount)); } } /** * @dev Owner finalizes the issue and distributes the bepro or rejects the PR * @param _issueID issue id (mapping with github) * @param _prAddresses PR Address * @param _prAmounts PR Amounts */ function proposeIssueMerge(uint256 _issueID, address[] memory _prAddresses, uint256[] memory _prAmounts) public whenNotPaused { Issue memory issue = issues[_issueID]; require(issue._id != 0 , "Issue has to exist"); require(issue.finalized == false, "Issue has to be opened"); require(_prAmounts.length == _prAddresses.length, "Amounts has to equal addresses length"); require(beproToken.balanceOf(msg.sender) > COUNCIL_BEPRO_AMOUNT*10**18, "To propose merges the proposer has to be a Council (COUNCIL_BEPRO_AMOUNT)"); MergeProposal memory mergeProposal; mergeProposal._id = issue.mergeIDIncrement; mergeProposal.prAmounts = _prAmounts; mergeProposal.prAddresses = _prAddresses; mergeProposal.proposalAddress = msg.sender; uint256 total = ((issues[_issueID].beproStaked * (feeShare + mergeCreatorFeeShare)) / 100); // Fee + Merge Creator Fee + 0 for(uint i = 0; i < _prAddresses.length; i++){ require(beproToken.balanceOf(_prAddresses[i]) > DEVELOPER_BEPRO_AMOUNT*10**18, "To receive development rewards the rewarded has to be a Developer (DEVELOPER_BEPRO_AMOUNT)"); total = total.add((_prAmounts[i] * (100-feeShare-mergeCreatorFeeShare)) / 100); } require(total == issues[_issueID].beproStaked, "Totals dont match"); issues[_issueID].mergeProposals[issue.mergeIDIncrement] = mergeProposal; issues[_issueID].mergeIDIncrement = issues[_issueID].mergeIDIncrement + 1; emit MergeProposalCreated(_issueID, mergeProposal._id, msg.sender); } /** * @dev Owner finalizes the issue and distributes the bepro or rejects the PR * @param _issueID issue id (mapping with github) * @param _mergeID merge id */ function closeIssue(uint256 _issueID, uint256 _mergeID) public whenNotPaused { Issue memory issue = issues[_issueID]; require(issue._id != 0 , "Issue has to exist"); require(issue.finalized == false, "Issue has to be opened"); require(issue.mergeIDIncrement > _mergeID, "Merge Proposal does not exist"); require(isMergeApproved(_issueID, _mergeID), "Issue has to have passed voting"); require(!isMergeDisputed(_issueID, _mergeID), "Merge has been disputed"); require(isMergeTheOneWithMoreVotes(_issueID, _mergeID), "There is a merge proposal with more votes"); // Closes the issue issues[_issueID].finalized = true; MergeProposal memory merge = issues[_issueID].mergeProposals[_mergeID]; // Fee Transfer require(beproToken.transfer(feeAddress, (issues[_issueID].beproStaked * feeShare) / 100), "Has to transfer"); // Merge Creator Transfer require(beproToken.transfer(feeAddress, (issues[_issueID].beproStaked * mergeCreatorFeeShare) / 100), "Has to transfer"); // Generate Reputation Tokens for(uint i = 0; i < merge.prAddresses.length; i++){ myIssues[merge.prAddresses[i]].push(_issueID); require(beproToken.transfer(merge.prAddresses[i], (merge.prAmounts[i] * (100-feeShare-mergeCreatorFeeShare)) / 100), "Has to transfer"); } closedIdsCount = closedIdsCount.add(1); totalStaked = totalStaked.sub(issue.beproStaked); emit CloseIssue(_issueID, _mergeID, merge.prAddresses); } function getIssuesByAddress(address _address) public returns (uint256[] memory){ return myIssues[_address]; } function getVotesByAddress(address _address) public returns (uint256){ Voter storage voter = voters[_address]; return voter.votesDelegatedByOthers.add(voter.votesDelegated[_address]); } function getIssueById(uint256 _issueID) public returns (uint256, uint256, uint256, address, uint256, uint256, bool, bool){ Issue memory issue = issues[_issueID]; return (issue._id, issue.beproStaked, issue.creationDate, issue.issueGenerator, issue.votesForApprove, issue.mergeIDIncrement, issue.finalized, issue.canceled); } function getMergeById(uint256 _issueID, uint256 _mergeId) public returns (uint256, uint256, uint256, address[] memory, uint256[] memory, address){ MergeProposal memory merge = issues[_issueID].mergeProposals[_mergeId]; return (merge._id, merge.votes, merge.disputes, merge.prAddresses, merge.prAmounts, merge.proposalAddress); } /** * @dev Change BEPRO Token Address (Upgrade) */ function changeBEPROAddress(address _newAddress) public onlyOwner { beproToken = _IERC20(_newAddress); } /** * @dev Change Fee Address */ function editFeeAddress(address _newAddress) public onlyOwner { feeAddress = _newAddress; } /** * @dev Change Share Fee Amount */ function editFeeShare(uint256 _feeShare) public onlyOwner { feeShare = _feeShare; } /** * @dev Upgrade Contract Version */ function upgradeContract(address _newContract) public onlyOwner whenPaused { //To be done } }
Change Share Fee Amount/
function editFeeShare(uint256 _feeShare) public onlyOwner { feeShare = _feeShare; }
12,737,468
// SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {BytesLib} from "../integrations/uniswap/BytesLib.sol"; import {AddressProvider} from "../core/AddressProvider.sol"; import {ContractsRegister} from "../core/ContractsRegister.sol"; import {IWETHGateway} from "../interfaces/IWETHGateway.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {ISwapRouter} from "../integrations/uniswap/IUniswapV3.sol"; import {IUniswapV2Router02} from "../integrations/uniswap/IUniswapV2Router02.sol"; import {ICurvePool} from "../integrations/curve/ICurvePool.sol"; import {IYVault} from "../integrations/yearn/IYVault.sol"; import {IWETH} from "../interfaces/external/IWETH.sol"; import {YearnAdapter} from "../adapters/YearnV2.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; contract LeveragedActions is ReentrancyGuard { using SafeMath for uint256; using Address for address payable; using Address for address; using SafeERC20 for IERC20; using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; uint256 private constant FEE_SIZE = 3; /// @dev Contracts reggister to check that credit manager is registered in Gearbox ContractsRegister public immutable contractsRegister; /// @dev address of WETH token address public wethToken; /// @dev WETH Gateway for opening ETH credit account IWETHGateway public wethGateway; struct LongParameters { address creditManager; uint256 leverageFactor; uint256 swapInterface; address swapContract; bytes swapCalldata; uint256 lpInterface; address lpContract; uint256 amountOutMin; } // Emits each time new action is done event Action( address indexed tokenIn, address indexed collateral, address indexed asset, uint256 amountIn, address shortSwapContract, address longSwapContract, address lpContract, uint256 referralCode ); // Contract version uint constant public version = 1; modifier registeredCreditManagersOnly(address creditManager) { require( contractsRegister.isCreditManager(creditManager), Errors.REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY ); _; } constructor(address _addressProvider) { require( _addressProvider != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); AddressProvider addressProvider = AddressProvider(_addressProvider); contractsRegister = ContractsRegister( addressProvider.getContractsRegister() ); wethGateway = IWETHGateway(addressProvider.getWETHGateway()); wethToken = addressProvider.getWethToken(); } /// @dev Opens short position (for example, swap USDC to ETH, open credit account in ETH, then swap all ETH on account to USDC) /// @param router UniswapV2 router to use for exchange /// @param amountIn Amount in, if you send ETH as value- it would be taken from msg.value /// @param amountOutMin Minimal amount after first swap before opening account /// @param path UniswapV2 path for short swap /// @param longParams parameters for long operation /// @param referralCode referral code, it'll be in Action event and in openCreditAccount also function openShortUniV2( address router, uint256 amountIn, uint256 amountOutMin, address[] memory path, uint256 deadline, LongParameters calldata longParams, uint256 referralCode ) external payable nonReentrant { address collateral = ICreditManager(longParams.creditManager) .underlyingToken(); require(path.length > 1, Errors.INCORRECT_PATH_LENGTH); require( path[path.length - 1] == collateral, Errors.LA_TOKEN_OUT_IS_NOT_COLLATERAL ); bytes memory data = abi.encodeWithSelector( bytes4(0x38ed1739), // "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)", amountIn, amountOutMin, path, address(this), deadline ); // M:[LA-5] _openShort( router, path[0], amountIn, collateral, data, longParams, referralCode ); // M:[LA-5] } /// @dev Opens short position (for example, swap USDC to ETH, open credit account in ETH, then swap all ETH to USDC) /// @param router UniswapV3 router (ISwapRouter) to use for exchange /// @param paramsV3 Parameters UniV# exact input for short swap operation /// @param referralCode referral code, it'll be in Action event and in openCreditAccount also function openShortUniV3( address router, ISwapRouter.ExactInputParams memory paramsV3, LongParameters calldata longParams, uint256 referralCode ) external payable nonReentrant { address collateral = ICreditManager(longParams.creditManager) .underlyingToken(); // Getting initial token from short paremeters (address tokenIn, address tokenOut) = _extractTokensUniV3( paramsV3.path ); // M:[LA-6] require(tokenOut == collateral, Errors.LA_TOKEN_OUT_IS_NOT_COLLATERAL); // Changes recipient to this contract paramsV3.recipient = address(this); // M:[LA-6] bytes memory data = abi.encodeWithSelector( bytes4(0xc04b8d59), // + paramsV3 ); // M:[LA-6] _openShort( router, tokenIn, paramsV3.amountIn, collateral, data, longParams, referralCode ); // M:[LA-6] } /// @dev Opens short position (for example, swap USDC to ETH, open credit account in ETH, then swap all ETH to USDC) /// @param curvePool Curve pool address /// @param i Index value for the coin to send /// @param j Index value of the coin to receive /// @param amountIn Amount in, if you send ETH as value- it would be taken from msg.value /// @param amountOutMin Minimal amount after first swap before opening account /// @param longParams parameters for long operation /// @param referralCode referral code, it'll be in Action event and in openCreditAccount also function openShortCurve( address curvePool, int128 i, int128 j, uint256 amountIn, uint256 amountOutMin, LongParameters calldata longParams, uint256 referralCode ) external payable nonReentrant { address collateral = ICreditManager(longParams.creditManager) .underlyingToken(); address tokenIn = ICurvePool(curvePool).coins(uint256(i)); // M:[LA-1] address tokenOut = ICurvePool(curvePool).coins(uint256(j)); // M:[LA-1] require(tokenOut == collateral, Errors.LA_TOKEN_OUT_IS_NOT_COLLATERAL); bytes memory data = abi.encodeWithSelector( bytes4(0x3df02124), //"exchange(int128,int128,uint256,uint256)" i, j, amountIn, amountOutMin ); // M:[LA-7] _openShort( curvePool, tokenIn, amountIn, collateral, data, longParams, referralCode ); // M:[LA-7] } /// @dev Opens long position (for example, open credit account in ETH, then swap all ETH to USDC) /// @param amountIn Amount in, if you send ETH as value- it would be taken from msg.value /// @param longParams parameters for long operation /// @param referralCode referral code, it'll be in Action event and in openCreditAccount also function openLong( uint256 amountIn, LongParameters calldata longParams, uint256 referralCode ) external payable nonReentrant { address collateral = ICreditManager(longParams.creditManager) .underlyingToken(); // M:[LA-1] uint256 balanceBefore = IERC20(collateral).balanceOf(address(this)); _getTokenOrWrapETH(collateral, amountIn); // M:[LA-1] address asset = _openLong( IERC20(collateral).balanceOf(address(this)).sub(balanceBefore), longParams, referralCode ); // M:[LA-1] emit Action( collateral, collateral, asset, amountIn, address(0), longParams.swapContract, longParams.lpContract, referralCode ); // M:[LA-1] } /// @dev Opens leveraged account and put all money into LP Contract (Yearn for example) function openLP( address creditManager, uint256 leverageFactor, uint256 amountIn, uint256 lpInterface, address lpContract, uint256 amountOutMin, uint256 referralCode ) external payable registeredCreditManagersOnly(creditManager) nonReentrant { // Gets collateral address collateral = ICreditManager(creditManager).underlyingToken(); // M:[LA-8] uint256 balanceBefore = IERC20(collateral).balanceOf(address(this)); // Transgers tokens / wraps ETH _getTokenOrWrapETH(collateral, amountIn); // M:[LA-8] // Provide needed allowance _provideCreditAccountAllowance(creditManager, collateral); // M:[LA-8] // Opens credit account ICreditManager(creditManager).openCreditAccount( IERC20(collateral).balanceOf(address(this)).sub(balanceBefore), address(this), leverageFactor, referralCode ); // Deposits LP address lpAsset = _depositLP(creditManager, lpInterface, lpContract); // M:[LA-8] require( IERC20(lpAsset).balanceOf( ICreditManager(creditManager).getCreditAccountOrRevert( address(this) ) ) >= amountOutMin, Errors.LA_LOWER_THAN_AMOUNT_MIN ); // Transfers ownership to msg.sender ICreditManager(creditManager).transferAccountOwnership(msg.sender); // M:[LA-8] // Emits actions emit Action( collateral, collateral, lpAsset, amountIn, address(0), address(0), lpContract, referralCode ); // M:[LA-8] } function _openShort( address shortSwapContract, address tokenIn, uint256 amountIn, address collateral, bytes memory shortSwapCalldata, LongParameters calldata longParams, uint256 referralCode ) internal { // Checks that swapContract is allowed _getAdapterOrRevert(longParams.creditManager, shortSwapContract); // M:[LA-5, 6, 7] // Transfers tokens from msg.sender to contract _getTokenOrWrapETH(tokenIn, amountIn); // M:[LA-5, 6, 7] uint256 balanceBefore = IERC20(collateral).balanceOf(address(this)); // Provides enough allowance to swapContract _provideCreditAccountAllowance(shortSwapContract, tokenIn); // M:[LA-5, 6, 7] // Calls short swap shortSwapContract.functionCall(shortSwapCalldata); // M:[LA-5, 6, 7] // Opens long position and transfer ownership address asset = _openLong( IERC20(collateral).balanceOf(address(this)).sub(balanceBefore), longParams, referralCode ); // M:[LA-5, 6, 7] // Returns tokens if they exists on this contract _returnTokenOrUnwrapWETH(tokenIn); // M:[LA-5, 6, 7] // Emits action emit Action( tokenIn, collateral, asset, amountIn, shortSwapContract, longParams.swapContract, longParams.lpContract, referralCode ); // M:[LA-5, 6, 7] } /// @dev Opens position: open account with desired le /// - opens account with desired leerage factor /// - transfers all assets using provided adapter to desired asset /// - executes lp operation, if provided function _openLong( uint256 amount, LongParameters calldata longParams, uint256 referralCode ) internal registeredCreditManagersOnly(longParams.creditManager) returns (address asset) { address collateral = ICreditManager(longParams.creditManager) .underlyingToken(); // M:[LA-1] // uint256 amount = IERC20(collateral).balanceOf(address(this)); // M:[LA-1] _provideCreditAccountAllowance(longParams.creditManager, collateral); // M:[LA-1] ICreditManager(longParams.creditManager).openCreditAccount( amount, address(this), longParams.leverageFactor, referralCode ); // M:[LA-1] address creditAccount = ICreditManager(longParams.creditManager) .getCreditAccountOrRevert(address(this)); uint256 leveragedAmount = IERC20(collateral).balanceOf(creditAccount); // M:[LA-1] address adapter = _getAdapterOrRevert( longParams.creditManager, longParams.swapContract ); // // UNISWAP V2 INTERFACE // if (longParams.swapInterface == Constants.UNISWAP_V2) { ( uint256 amountIn, uint256 amountOutMin, address[] memory path, , uint256 deadline ) = abi.decode( longParams.swapCalldata, (uint256, uint256, address[], address, uint256) ); // M:[LA-1] uint256 amountOutMinLeveraged = amountOutMin .mul(leveragedAmount) .div(amountIn); // M:[LA-1] IUniswapV2Router02(adapter).swapExactTokensForTokens( leveragedAmount, amountOutMinLeveraged, path, address(this), // it will be replaced in adapter deadline ); // M:[LA-1] require(path[0] == collateral, Errors.INCORRECT_PARAMETER); asset = path[path.length - 1]; // M:[LA-1] } // // UNISWAP V3 INTERFACE // else if (longParams.swapInterface == Constants.UNISWAP_V3) { ISwapRouter.ExactInputParams memory params = abi.decode( longParams.swapCalldata, (ISwapRouter.ExactInputParams) ); params.amountOutMinimum = params .amountOutMinimum .mul(leveragedAmount) .div(params.amountIn); params.amountIn = leveragedAmount; ISwapRouter(adapter).exactInput(params); (, asset) = _extractTokensUniV3(params.path); } // // CURVE V1 INTERFACE // else if (longParams.swapInterface == Constants.CURVE_V1) { (int128 i, int128 j, uint256 dx, uint256 min_dy) = abi.decode( longParams.swapCalldata, (int128, int128, uint256, uint256) ); ICurvePool(adapter).exchange( i, j, leveragedAmount, min_dy.mul(leveragedAmount).div(dx) ); asset = ICurvePool(longParams.swapContract).coins(uint256(j)); } else { revert(Errors.LA_UNKNOWN_SWAP_INTERFACE); // Todo: } // // LP // if (longParams.lpContract != address(0)) { asset = _depositLP( longParams.creditManager, longParams.lpInterface, longParams.lpContract ); // M:[LA-2] } require( IERC20(asset).balanceOf(creditAccount) >= longParams.amountOutMin, Errors.LA_LOWER_THAN_AMOUNT_MIN ); ICreditManager(longParams.creditManager).transferAccountOwnership( msg.sender ); // M:[LA-1, 2, 3, 4] } /// @dev Opens LP position for whole money on account /// @param creditManager Address of creditManager /// @param lpInterface LP Interface /// @param lpContract Address of LP contract /// @return LP asset address function _depositLP( address creditManager, uint256 lpInterface, address lpContract ) internal returns (address) { address lpAdapter = _getAdapterOrRevert(creditManager, lpContract); if (lpInterface == Constants.LP_YEARN) { IYVault(lpAdapter).deposit(); // M: [LA-2] return lpContract; } revert(Errors.LA_UNKNOWN_LP_INTERFACE); } /// @dev Transfers money from msg.sender account or convert from eth if /// @param token Address on token /// @param amountIn Amount of tokens to be transferred. If value is attached to tx, it should be equal amountIn function _getTokenOrWrapETH(address token, uint256 amountIn) internal { if (token == wethToken && msg.value > 0) { require(msg.value == amountIn, Errors.LA_INCORRECT_VALUE); // M:[LA-12] IWETH(wethToken).deposit{value: msg.value}(); // M:[LA-2, ] } else { require(msg.value == 0, Errors.LA_HAS_VALUE_WITH_TOKEN_TRANSFER); // M:[LA-11] IERC20(token).safeTransferFrom(msg.sender, address(this), amountIn); // M:[LA-1,3,4,5,6,7,8] } } /// @dev Transfers unused tokens back or ETH if it's wethToken /// @param token Address of token function _returnTokenOrUnwrapWETH(address token) internal { // Checks balanceAfter and returns money if not all tokens were converted uint256 balance = IERC20(token).balanceOf(address(this)); // // M:[LA-13, 14] if (balance > 0) { if (token == wethToken) { IWETH(wethToken).withdraw(balance); // M:[LA-14] payable(msg.sender).sendValue(balance); // M:[LA-14] } else { IERC20(token).safeTransfer(msg.sender, balance); // M:[LA-13] } } } /// @dev Returns adapter for provided contract or reverts if it's now allowed /// @param creditManager Address of credit manager /// @param targetContract Address of contract which adapter is needed function _getAdapterOrRevert(address creditManager, address targetContract) internal view returns (address) { // Could be optimised by adding internal list of creditManagers ICreditFilter creditFilter = ICreditFilter( ICreditManager(creditManager).creditFilter() ); // M:[LA-10] address adapter = creditFilter.contractToAdapter(targetContract); require( adapter != address(0), Errors.CF_CONTRACT_IS_NOT_IN_ALLOWED_LIST ); // M:[LA-10] return adapter; } /// @dev Extracts from and to tokens from UniV3 path /// @param path UniV3 encoded path /// @return tokenA tokenIn /// @return tokenB tokenOut function _extractTokensUniV3(bytes memory path) internal pure returns (address tokenA, address tokenB) { require( path.length >= 2 * ADDR_SIZE + FEE_SIZE, Errors.INCORRECT_PATH_LENGTH ); tokenA = path.toAddress(0); tokenB = path.toAddress(path.length - ADDR_SIZE); } /// @dev Checks that credit account has enough allowance for operation by comparing existing one with x10 times more than needed /// @param targetContract Contract to check allowance /// @param token Token address of contract function _provideCreditAccountAllowance( address targetContract, address token ) internal { // Get 10x reserve in allowance if ( IERC20(token).allowance(address(this), targetContract) < Constants.MAX_INT_4 ) { IERC20(token).safeApprove(targetContract, 0); // M:[LA-1,2,3,4,] IERC20(token).safeApprove(targetContract, Constants.MAX_INT); // M:[LA-1,2,3,4] } } function isTransferAllowed(address creditManager) external view returns (bool) { ICreditFilter creditFilter = ICreditFilter( ICreditManager(creditManager).creditFilter() ); return creditFilter.allowanceForAccountTransfers( address(this), msg.sender ); } receive() external payable {} // M:[LA-14] } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT 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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author GonΓ§alo SΓ‘ <[emailΒ protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore( 0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. ) ) } return tempBytes; } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add( add( add(_bytes, lengthmod), mul(0x20, iszero(lengthmod)) ), _start ) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div( mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000 ) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3, "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {IAppAddressProvider} from "../interfaces/app/IAppAddressProvider.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title AddressRepository /// @notice Stores addresses of deployed contracts contract AddressProvider is Ownable, IAppAddressProvider { // Mapping which keeps all addresses mapping(bytes32 => address) public addresses; // Emits each time when new address is set event AddressSet(bytes32 indexed service, address indexed newAddress); // This event is triggered when a call to ClaimTokens succeeds. event Claimed(uint256 user_id, address account, uint256 amount, bytes32 leaf); // Repositories & services bytes32 public constant CONTRACTS_REGISTER = "CONTRACTS_REGISTER"; bytes32 public constant ACL = "ACL"; bytes32 public constant PRICE_ORACLE = "PRICE_ORACLE"; bytes32 public constant ACCOUNT_FACTORY = "ACCOUNT_FACTORY"; bytes32 public constant DATA_COMPRESSOR = "DATA_COMPRESSOR"; bytes32 public constant TREASURY_CONTRACT = "TREASURY_CONTRACT"; bytes32 public constant GEAR_TOKEN = "GEAR_TOKEN"; bytes32 public constant WETH_TOKEN = "WETH_TOKEN"; bytes32 public constant WETH_GATEWAY = "WETH_GATEWAY"; bytes32 public constant LEVERAGED_ACTIONS = "LEVERAGED_ACTIONS"; // Contract version uint256 public constant version = 1; constructor() { // @dev Emits first event for contract discovery emit AddressSet("ADDRESS_PROVIDER", address(this)); } /// @return Address of ACL contract function getACL() external view returns (address) { return _getAddress(ACL); // T:[AP-3] } /// @dev Sets address of ACL contract /// @param _address Address of ACL contract function setACL(address _address) external onlyOwner // T:[AP-15] { _setAddress(ACL, _address); // T:[AP-3] } /// @return Address of ContractsRegister function getContractsRegister() external view returns (address) { return _getAddress(CONTRACTS_REGISTER); // T:[AP-4] } /// @dev Sets address of ContractsRegister /// @param _address Address of ContractsRegister function setContractsRegister(address _address) external onlyOwner // T:[AP-15] { _setAddress(CONTRACTS_REGISTER, _address); // T:[AP-4] } /// @return Address of PriceOracle function getPriceOracle() external view override returns (address) { return _getAddress(PRICE_ORACLE); // T:[AP-5] } /// @dev Sets address of PriceOracle /// @param _address Address of PriceOracle function setPriceOracle(address _address) external onlyOwner // T:[AP-15] { _setAddress(PRICE_ORACLE, _address); // T:[AP-5] } /// @return Address of AccountFactory function getAccountFactory() external view returns (address) { return _getAddress(ACCOUNT_FACTORY); // T:[AP-6] } /// @dev Sets address of AccountFactory /// @param _address Address of AccountFactory function setAccountFactory(address _address) external onlyOwner // T:[AP-15] { _setAddress(ACCOUNT_FACTORY, _address); // T:[AP-7] } /// @return Address of AccountFactory function getDataCompressor() external view override returns (address) { return _getAddress(DATA_COMPRESSOR); // T:[AP-8] } /// @dev Sets address of AccountFactory /// @param _address Address of AccountFactory function setDataCompressor(address _address) external onlyOwner // T:[AP-15] { _setAddress(DATA_COMPRESSOR, _address); // T:[AP-8] } /// @return Address of Treasury contract function getTreasuryContract() external view returns (address) { return _getAddress(TREASURY_CONTRACT); //T:[AP-11] } /// @dev Sets address of Treasury Contract /// @param _address Address of Treasury Contract function setTreasuryContract(address _address) external onlyOwner // T:[AP-15] { _setAddress(TREASURY_CONTRACT, _address); //T:[AP-11] } /// @return Address of GEAR token function getGearToken() external view override returns (address) { return _getAddress(GEAR_TOKEN); // T:[AP-12] } /// @dev Sets address of GEAR token /// @param _address Address of GEAR token function setGearToken(address _address) external onlyOwner // T:[AP-15] { _setAddress(GEAR_TOKEN, _address); // T:[AP-12] } /// @return Address of WETH token function getWethToken() external view override returns (address) { return _getAddress(WETH_TOKEN); // T:[AP-13] } /// @dev Sets address of WETH token /// @param _address Address of WETH token function setWethToken(address _address) external onlyOwner // T:[AP-15] { _setAddress(WETH_TOKEN, _address); // T:[AP-13] } /// @return Address of WETH token function getWETHGateway() external view override returns (address) { return _getAddress(WETH_GATEWAY); // T:[AP-14] } /// @dev Sets address of WETH token /// @param _address Address of WETH token function setWETHGateway(address _address) external onlyOwner // T:[AP-15] { _setAddress(WETH_GATEWAY, _address); // T:[AP-14] } /// @return Address of WETH token function getLeveragedActions() external view override returns (address) { return _getAddress(LEVERAGED_ACTIONS); // T:[AP-7] } /// @dev Sets address of WETH token /// @param _address Address of WETH token function setLeveragedActions(address _address) external onlyOwner // T:[AP-15] { _setAddress(LEVERAGED_ACTIONS, _address); // T:[AP-7] } /// @return Address of key, reverts if key doesn't exist function _getAddress(bytes32 key) internal view returns (address) { address result = addresses[key]; require(result != address(0), Errors.AS_ADDRESS_NOT_FOUND); // T:[AP-1] return result; // T:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] } /// @dev Sets address to map by its key /// @param key Key in string format /// @param value Address function _setAddress(bytes32 key, address value) internal { addresses[key] = value; // T:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] emit AddressSet(key, value); // T:[AP-2] } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Errors} from "../libraries/helpers/Errors.sol"; import {ACLTrait} from "./ACLTrait.sol"; /// @title Pools & Contract managers registry /// @notice Keeps pools & contract manager addresses contract ContractsRegister is ACLTrait { // Pools list address[] public pools; mapping(address => bool) public isPool; // Credit Managers list address[] public creditManagers; mapping(address => bool) public isCreditManager; // Contract version uint256 public constant version = 1; // emits each time when new pool was added to register event NewPoolAdded(address indexed pool); // emits each time when new credit Manager was added to register event NewCreditManagerAdded(address indexed creditManager); constructor(address addressProvider) ACLTrait(addressProvider) {} /// @dev Adds pool to list /// @param newPoolAddress Address on new pool added function addPool(address newPoolAddress) external configuratorOnly // T:[CR-1] { require( newPoolAddress != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); require(!isPool[newPoolAddress], Errors.CR_POOL_ALREADY_ADDED); // T:[CR-2] pools.push(newPoolAddress); // T:[CR-3] isPool[newPoolAddress] = true; // T:[CR-3] emit NewPoolAdded(newPoolAddress); // T:[CR-4] } /// @dev Returns array of registered pool addresses function getPools() external view returns (address[] memory) { return pools; } /// @return Returns quantity of registered pools function getPoolsCount() external view returns (uint256) { return pools.length; // T:[CR-3] } /// @dev Adds credit accounts manager address to the registry /// @param newCreditManager Address on new pausableAdmin added function addCreditManager(address newCreditManager) external configuratorOnly // T:[CR-1] { require( newCreditManager != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); require( !isCreditManager[newCreditManager], Errors.CR_CREDIT_MANAGER_ALREADY_ADDED ); // T:[CR-5] creditManagers.push(newCreditManager); // T:[CR-6] isCreditManager[newCreditManager] = true; // T:[CR-6] emit NewCreditManagerAdded(newCreditManager); // T:[CR-7] } /// @dev Returns array of registered credit manager addresses function getCreditManagers() external view returns (address[] memory) { return creditManagers; } /// @return Returns quantity of registered credit managers function getCreditManagersCount() external view returns (uint256) { return creditManagers.length; // T:[CR-6] } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; interface IWETHGateway { /// @dev convert ETH to WETH and add liqudity to pool /// @param pool Address of PoolService contract which where user wants to add liquidity. This pool should has WETH as underlying asset /// @param onBehalfOf The address that will receive the diesel tokens, same as msg.sender if the user wants to receive them on his /// own wallet, or a different address if the beneficiary of diesel tokens is a different wallet /// @param referralCode Code used to register the integrator originating the operation, for potential rewards. /// 0 if the action is executed directly by the user, without any middle-man function addLiquidityETH( address pool, address onBehalfOf, uint16 referralCode ) external payable; /// @dev Removes liquidity from pool and convert WETH to ETH /// - burns lp's diesel (LP) tokens /// - returns underlying tokens to lp /// @param pool Address of PoolService contract which where user wants to withdraw liquidity. This pool should has WETH as underlying asset /// @param amount Amount of tokens to be transfer /// @param to Address to transfer liquidity function removeLiquidityETH( address pool, uint256 amount, address payable to ) external; /// @dev Opens credit account in ETH /// @param creditManager Address of credit Manager. Should used WETH as underlying asset /// @param onBehalfOf The address that we open credit account. Same as msg.sender if the user wants to open it for his own wallet, /// or a different address if the beneficiary is a different wallet /// @param leverageFactor Multiplier to borrowers own funds /// @param referralCode Code used to register the integrator originating the operation, for potential rewards. /// 0 if the action is executed directly by the user, without any middle-man function openCreditAccountETH( address creditManager, address payable onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external payable; /// @dev Repays credit account in ETH /// - transfer borrowed money with interest + fee from borrower account to pool /// - transfer all assets to "to" account /// @param creditManager Address of credit Manager. Should used WETH as underlying asset /// @param to Address to send credit account assets function repayCreditAccountETH(address creditManager, address to) external payable; function addCollateralETH(address creditManager, address onBehalfOf) external payable; /// @dev Unwrap WETH => ETH /// @param to Address to send eth /// @param amount Amount of WETH was transferred function unwrapWETH(address to, uint256 amount) external; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {IAppCreditManager} from "./app/IAppCreditManager.sol"; import {DataTypes} from "../libraries/data/Types.sol"; /// @title Credit Manager interface /// @notice It encapsulates business logic for managing credit accounts /// /// More info: https://dev.gearbox.fi/developers/credit/credit_manager interface ICreditManager is IAppCreditManager { // Emits each time when the credit account is opened event OpenCreditAccount( address indexed sender, address indexed onBehalfOf, address indexed creditAccount, uint256 amount, uint256 borrowAmount, uint256 referralCode ); // Emits each time when the credit account is closed event CloseCreditAccount( address indexed owner, address indexed to, uint256 remainingFunds ); // Emits each time when the credit account is liquidated event LiquidateCreditAccount( address indexed owner, address indexed liquidator, uint256 remainingFunds ); // Emits each time when borrower increases borrowed amount event IncreaseBorrowedAmount(address indexed borrower, uint256 amount); // Emits each time when borrower adds collateral event AddCollateral( address indexed onBehalfOf, address indexed token, uint256 value ); // Emits each time when the credit account is repaid event RepayCreditAccount(address indexed owner, address indexed to); // Emit each time when financial order is executed event ExecuteOrder(address indexed borrower, address indexed target); // Emits each time when new fees are set event NewParameters( uint256 minAmount, uint256 maxAmount, uint256 maxLeverage, uint256 feeInterest, uint256 feeLiquidation, uint256 liquidationDiscount ); event TransferAccount(address indexed oldOwner, address indexed newOwner); // // CREDIT ACCOUNT MANAGEMENT // /** * @dev Opens credit account and provides credit funds. * - Opens credit account (take it from account factory) * - Transfers trader /farmers initial funds to credit account * - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract. * - Emits OpenCreditAccount event * Function reverts if user has already opened position * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account * * @param amount Borrowers own funds * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param leverageFactor Multiplier to borrowers own funds * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function openCreditAccount( uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external override; /** * @dev Closes credit account * - Swaps all assets to underlying one using default swap protocol * - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount * - Transfers remaining funds to the trader / farmer * - Closes the credit account and return it to account factory * - Emits CloseCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account * * @param to Address to send remaining funds * @param paths Exchange type data which provides paths + amountMinOut */ function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths) external override; /** * @dev Liquidates credit account * - Transfers discounted total credit account value from liquidators account * - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner * - Transfer all assets from credit account to liquidator ("to") account * - Returns credit account to factory * - Emits LiquidateCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account * * @param borrower Borrower address * @param to Address to transfer all assets from credit account * @param force If true, use transfer function for transferring tokens instead of safeTransfer */ function liquidateCreditAccount( address borrower, address to, bool force ) external; /// @dev Repays credit account /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account /// /// @param to Address to send credit account assets function repayCreditAccount(address to) external override; /// @dev Repays credit account with ETH. Restricted to be called by WETH Gateway only /// /// @param borrower Address of borrower /// @param to Address to send credit account assets function repayCreditAccountETH(address borrower, address to) external returns (uint256); /// @dev Increases borrowed amount by transferring additional funds from /// the pool if after that HealthFactor > minHealth /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount /// /// @param amount Amount to increase borrowed amount function increaseBorrowedAmount(uint256 amount) external override; /// @dev Adds collateral to borrower's credit account /// @param onBehalfOf Address of borrower to add funds /// @param token Token address /// @param amount Amount to add function addCollateral( address onBehalfOf, address token, uint256 amount ) external override; /// @dev Returns true if the borrower has opened a credit account /// @param borrower Borrower account function hasOpenedCreditAccount(address borrower) external view override returns (bool); /// @dev Calculates Repay amount = borrow amount + interest accrued + fee /// /// More info: https://dev.gearbox.fi/developers/credit/economy#repay /// https://dev.gearbox.fi/developers/credit/economy#liquidate /// /// @param borrower Borrower address /// @param isLiquidated True if calculated repay amount for liquidator function calcRepayAmount(address borrower, bool isLiquidated) external view override returns (uint256); /// @dev Returns minimal amount for open credit account function minAmount() external view returns (uint256); /// @dev Returns maximum amount for open credit account function maxAmount() external view returns (uint256); /// @dev Returns maximum leveraged factor allowed for this pool function maxLeverageFactor() external view returns (uint256); /// @dev Returns underlying token address function underlyingToken() external view returns (address); /// @dev Returns address of connected pool function poolService() external view returns (address); /// @dev Returns address of CreditFilter function creditFilter() external view returns (ICreditFilter); /// @dev Returns address of CreditFilter function creditAccounts(address borrower) external view returns (address); /// @dev Executes filtered order on credit account which is connected with particular borrowers /// @param borrower Borrower address /// @param target Target smart-contract /// @param data Call data for call function executeOrder( address borrower, address target, bytes memory data ) external returns (bytes memory); /// @dev Approves token for msg.sender's credit account function approve(address targetContract, address token) external; /// @dev Approve tokens for credit accounts. Restricted for adapters only function provideCreditAccountAllowance( address creditAccount, address toContract, address token ) external; function transferAccountOwnership(address newOwner) external; /// @dev Returns address of borrower's credit account and reverts of borrower has no one. /// @param borrower Borrower address function getCreditAccountOrRevert(address borrower) external view override returns (address); // function feeSuccess() external view returns (uint256); function feeInterest() external view returns (uint256); function feeLiquidation() external view returns (uint256); function liquidationDiscount() external view returns (uint256); function minHealthFactor() external view returns (uint256); function defaultSwapContract() external view override returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; interface ICreditFilter { // Emits each time token is allowed or liquidtion threshold changed event TokenAllowed(address indexed token, uint256 liquidityThreshold); // Emits each time token is allowed or liquidtion threshold changed event TokenForbidden(address indexed token); // Emits each time contract is allowed or adapter changed event ContractAllowed(address indexed protocol, address indexed adapter); // Emits each time contract is forbidden event ContractForbidden(address indexed protocol); // Emits each time when fast check parameters are updated event NewFastCheckParameters(uint256 chiThreshold, uint256 fastCheckDelay); event TransferAccountAllowed( address indexed from, address indexed to, bool state ); event TransferPluginAllowed( address indexed pugin, bool state ); event PriceOracleUpdated(address indexed newPriceOracle); // // STATE-CHANGING FUNCTIONS // /// @dev Adds token to the list of allowed tokens /// @param token Address of allowed token /// @param liquidationThreshold The constant showing the maximum allowable ratio of Loan-To-Value for the i-th asset. function allowToken(address token, uint256 liquidationThreshold) external; /// @dev Adds contract to the list of allowed contracts /// @param targetContract Address of contract to be allowed /// @param adapter Adapter contract address function allowContract(address targetContract, address adapter) external; /// @dev Forbids contract and removes it from the list of allowed contracts /// @param targetContract Address of allowed contract function forbidContract(address targetContract) external; /// @dev Checks financial order and reverts if tokens aren't in list or collateral protection alerts /// @param creditAccount Address of credit account /// @param tokenIn Address of token In in swap operation /// @param tokenOut Address of token Out in swap operation /// @param amountIn Amount of tokens in /// @param amountOut Amount of tokens out function checkCollateralChange( address creditAccount, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut ) external; function checkMultiTokenCollateral( address creditAccount, uint256[] memory amountIn, uint256[] memory amountOut, address[] memory tokenIn, address[] memory tokenOut ) external; /// @dev Connects credit managaer, hecks that all needed price feeds exists and finalize config function connectCreditManager(address poolService) external; /// @dev Sets collateral protection for new credit accounts function initEnabledTokens(address creditAccount) external; function checkAndEnableToken(address creditAccount, address token) external; // // GETTERS // /// @dev Returns quantity of contracts in allowed list function allowedContractsCount() external view returns (uint256); /// @dev Returns of contract address from the allowed list by its id function allowedContracts(uint256 id) external view returns (address); /// @dev Reverts if token isn't in token allowed list function revertIfTokenNotAllowed(address token) external view; /// @dev Returns true if token is in allowed list otherwise false function isTokenAllowed(address token) external view returns (bool); /// @dev Returns quantity of tokens in allowed list function allowedTokensCount() external view returns (uint256); /// @dev Returns of token address from allowed list by its id function allowedTokens(uint256 id) external view returns (address); /// @dev Calculates total value for provided address /// More: https://dev.gearbox.fi/developers/credit/economy#total-value /// /// @param creditAccount Token creditAccount address function calcTotalValue(address creditAccount) external view returns (uint256 total); /// @dev Calculates Threshold Weighted Total Value /// More: https://dev.gearbox.fi/developers/credit/economy#threshold-weighted-value /// ///@param creditAccount Credit account address function calcThresholdWeightedValue(address creditAccount) external view returns (uint256 total); function contractToAdapter(address allowedContract) external view returns (address); /// @dev Returns address of underlying token function underlyingToken() external view returns (address); /// @dev Returns address & balance of token by the id of allowed token in the list /// @param creditAccount Credit account address /// @param id Id of token in allowed list /// @return token Address of token /// @return balance Token balance function getCreditAccountTokenById(address creditAccount, uint256 id) external view returns ( address token, uint256 balance, uint256 tv, uint256 twv ); /** * @dev Calculates health factor for the credit account * * sum(asset[i] * liquidation threshold[i]) * Hf = -------------------------------------------- * borrowed amount + interest accrued * * * More info: https://dev.gearbox.fi/developers/credit/economy#health-factor * * @param creditAccount Credit account address * @return Health factor in percents (see PERCENTAGE FACTOR in PercentageMath.sol) */ function calcCreditAccountHealthFactor(address creditAccount) external view returns (uint256); /// @dev Calculates credit account interest accrued /// More: https://dev.gearbox.fi/developers/credit/economy#interest-rate-accrued /// /// @param creditAccount Credit account address function calcCreditAccountAccruedInterest(address creditAccount) external view returns (uint256); /// @dev Return enabled tokens - token masks where each bit is "1" is token is enabled function enabledTokens(address creditAccount) external view returns (uint256); function liquidationThresholds(address token) external view returns (uint256); function priceOracle() external view returns (address); function updateUnderlyingTokenLiquidationThreshold() external; function revertIfCantIncreaseBorrowing( address creditAccount, uint256 minHealthFactor ) external view; function revertIfAccountTransferIsNotAllowed( address onwer, address creditAccount ) external view; function approveAccountTransfers(address from, bool state) external; function allowanceForAccountTransfers(address from, address to) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter { 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); } // SPDX-License-Identifier: GPL-2.0-or-later 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; function factory() external override view returns (address); function WETH() external override view returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external override returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external override 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 override returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external override 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 override 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 override returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external override returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external override returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external override payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external override returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external override returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external override payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external override view returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external override view returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external override view returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external override view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external override view returns (uint[] memory amounts); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.4; interface ICurvePool { function coins(uint256) external view returns (address); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IYVault is IERC20 { function token() external view returns (address); function deposit() external returns (uint256); function deposit(uint256 _amount) external returns (uint256); function deposit(uint256 _amount, address recipient) external returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function withdraw( uint256 maxShares, address recipient, uint256 maxLoss ) external returns (uint256); function pricePerShare() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.4; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {IYVault} from "../integrations/yearn/IYVault.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {CreditAccount} from "../credit/CreditAccount.sol"; import {CreditManager} from "../credit/CreditManager.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title Yearn adapter contract YearnAdapter is IYVault, ReentrancyGuard { using SafeMath for uint256; address public yVault; address public override token; ICreditManager public creditManager; ICreditFilter public creditFilter; /// @dev Constructor /// @param _creditManager Address Credit manager /// @param _yVault Address of yVault constructor(address _creditManager, address _yVault) { require( _creditManager != address(0) && _yVault != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); creditManager = ICreditManager(_creditManager); creditFilter = ICreditFilter(creditManager.creditFilter()); yVault = _yVault; // Check that we have token connected with this yearn pool token = IYVault(yVault).token(); creditFilter.revertIfTokenNotAllowed(token); } /// @dev Deposit credit account tokens to Yearn function deposit() external override nonReentrant returns (uint256) { // bytes4(0xd0e30db0) = deposit() return _deposit(abi.encodeWithSelector(bytes4(0xd0e30db0))); // M:[YA-1] } /// @dev Deposit credit account tokens to Yearn /// @param amount in tokens function deposit(uint256 amount) external override nonReentrant returns (uint256) { // bytes4(0xb6b55f25) = deposit return _deposit(abi.encodeWithSelector(bytes4(0xb6b55f25), amount)); // M:[YA-2] } /// @dev Deposit credit account tokens to Yearn /// @param amount in tokens function deposit(uint256 amount, address) external override nonReentrant returns (uint256) { // bytes4(0xb6b55f25) = deposit return _deposit(abi.encodeWithSelector(bytes4(0xb6b55f25), amount)); // M:[YA-2] } function _deposit(bytes memory data) internal returns (uint256 shares) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[YA-1,2] creditManager.provideCreditAccountAllowance( creditAccount, yVault, token ); // M:[YA-1,2] uint256 balanceInBefore = IERC20(token).balanceOf(creditAccount); // M:[YA-1,2] uint256 balanceOutBefore = IERC20(yVault).balanceOf(creditAccount); // M:[YA-1,2] shares = abi.decode( creditManager.executeOrder(msg.sender, yVault, data), (uint256) ); // M:[YA-1,2] creditFilter.checkCollateralChange( creditAccount, token, yVault, balanceInBefore.sub(IERC20(token).balanceOf(creditAccount)), IERC20(yVault).balanceOf(creditAccount).sub(balanceOutBefore) ); // M:[YA-1,2] } function withdraw() external override nonReentrant returns (uint256) { // bytes4(0x3ccfd60b) = withdraw() return _withdraw(abi.encodeWithSelector(bytes4(0x3ccfd60b))); // M:[YA-3] } function withdraw(uint256 maxShares) external override nonReentrant returns (uint256) { // bytes4(0x2e1a7d4d) = withdraw(uint256) return _withdraw(abi.encodeWithSelector(bytes4(0x2e1a7d4d), maxShares)); } function withdraw(uint256 maxShares, address) external override nonReentrant returns (uint256) { // Call the function with MaxShares only, cause recepient doesn't make sense here // bytes4(0x2e1a7d4d) = withdraw(uint256) return _withdraw(abi.encodeWithSelector(bytes4(0x2e1a7d4d), maxShares)); } /// @dev Withdraw yVaults from credit account /// @param maxShares How many shares to try and redeem for tokens, defaults to all. // @param recipient The address to issue the shares in this Vault to. Defaults to the caller's address. // @param maxLoss The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%. // If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal. // @return The quantity of tokens redeemed for `_shares`. function withdraw( uint256 maxShares, address, uint256 maxLoss ) public override nonReentrant returns (uint256 shares) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[YA-3] return _withdraw( abi.encodeWithSelector( bytes4(0xe63697c8), //"withdraw(uint256,address,uint256)", maxShares, creditAccount, maxLoss ) ); // M:[YA-3]) } function _withdraw(bytes memory data) internal returns (uint256 shares) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[YA-3] uint256 balanceInBefore = IERC20(yVault).balanceOf(creditAccount); // M:[YA-3] uint256 balanceOutBefore = IERC20(token).balanceOf(creditAccount); // M:[YA-3] shares = abi.decode( creditManager.executeOrder(msg.sender, yVault, data), (uint256) ); // M:[YA-3] creditFilter.checkCollateralChange( creditAccount, yVault, token, balanceInBefore.sub(IERC20(yVault).balanceOf(creditAccount)), IERC20(token).balanceOf(creditAccount).sub(balanceOutBefore) ); // M:[YA-3] } function pricePerShare() external view override returns (uint256) { return IYVault(yVault).pricePerShare(); } function name() external view override returns (string memory) { return IYVault(yVault).name(); } function symbol() external view override returns (string memory) { return IYVault(yVault).symbol(); } function decimals() external view override returns (uint8) { return IYVault(yVault).decimals(); } function allowance(address owner, address spender) external view override returns (uint256) { return IYVault(yVault).allowance(owner, spender); } function approve(address, uint256) external pure override returns (bool) { return true; } function balanceOf(address account) external view override returns (uint256) { return IYVault(yVault).balanceOf(account); } function totalSupply() external view override returns (uint256) { return IYVault(yVault).totalSupply(); } function transfer(address, uint256) external pure override returns (bool) { revert(Errors.NOT_IMPLEMENTED); } function transferFrom( address, address, uint256 ) external pure override returns (bool) { revert(Errors.NOT_IMPLEMENTED); } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {PercentageMath} from "../math/PercentageMath.sol"; library Constants { uint256 constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // 25% of MAX_INT uint256 constant MAX_INT_4 = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // REWARD FOR LEAN DEPLOYMENT MINING uint256 constant ACCOUNT_CREATION_REWARD = 1e5; uint256 constant DEPLOYMENT_COST = 1e17; // FEE = 10% uint256 constant FEE_INTEREST = 1000; // 10% // FEE + LIQUIDATION_FEE 2% uint256 constant FEE_LIQUIDATION = 200; // Liquidation premium 5% uint256 constant LIQUIDATION_DISCOUNTED_SUM = 9500; // 100% - LIQUIDATION_FEE - LIQUIDATION_PREMIUM uint256 constant UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD = LIQUIDATION_DISCOUNTED_SUM - FEE_LIQUIDATION; // Seconds in a year uint256 constant SECONDS_PER_YEAR = 365 days; uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = SECONDS_PER_YEAR * 3 /2; // 1e18 uint256 constant RAY = 1e27; uint256 constant WAD = 1e18; // OPERATIONS uint8 constant OPERATION_CLOSURE = 1; uint8 constant OPERATION_REPAY = 2; uint8 constant OPERATION_LIQUIDATION = 3; // Decimals for leverage, so x4 = 4*LEVERAGE_DECIMALS for openCreditAccount function uint8 constant LEVERAGE_DECIMALS = 100; // Maximum withdraw fee for pool in percentage math format. 100 = 1% uint8 constant MAX_WITHDRAW_FEE = 100; uint256 constant CHI_THRESHOLD = 9950; uint256 constant HF_CHECK_INTERVAL_DEFAULT = 4; uint256 constant NO_SWAP = 0; uint256 constant UNISWAP_V2 = 1; uint256 constant UNISWAP_V3 = 2; uint256 constant CURVE_V1 = 3; uint256 constant LP_YEARN = 4; uint256 constant EXACT_INPUT = 1; uint256 constant EXACT_OUTPUT = 2; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Errors library library Errors { // // COMMON // string public constant ZERO_ADDRESS_IS_NOT_ALLOWED = "Z0"; string public constant NOT_IMPLEMENTED = "NI"; string public constant INCORRECT_PATH_LENGTH = "PL"; string public constant INCORRECT_ARRAY_LENGTH = "CR"; string public constant REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY = "CP"; string public constant REGISTERED_POOLS_ONLY = "RP"; string public constant INCORRECT_PARAMETER = "IP"; // // MATH // string public constant MATH_MULTIPLICATION_OVERFLOW = "M1"; string public constant MATH_ADDITION_OVERFLOW = "M2"; string public constant MATH_DIVISION_BY_ZERO = "M3"; // // POOL // string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0"; string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1"; string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2"; string public constant POOL_INCORRECT_WITHDRAW_FEE = "PS3"; string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4"; // // CREDIT MANAGER // string public constant CM_NO_OPEN_ACCOUNT = "CM1"; string public constant CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT = "CM2"; string public constant CM_INCORRECT_AMOUNT = "CM3"; string public constant CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR = "CM4"; string public constant CM_CAN_UPDATE_WITH_SUCH_HEALTH_FACTOR = "CM5"; string public constant CM_WETH_GATEWAY_ONLY = "CM6"; string public constant CM_INCORRECT_PARAMS = "CM7"; string public constant CM_INCORRECT_FEES = "CM8"; string public constant CM_MAX_LEVERAGE_IS_TOO_HIGH = "CM9"; string public constant CM_CANT_CLOSE_WITH_LOSS = "CMA"; string public constant CM_TARGET_CONTRACT_iS_NOT_ALLOWED = "CMB"; string public constant CM_TRANSFER_FAILED = "CMC"; string public constant CM_INCORRECT_NEW_OWNER = "CME"; // // ACCOUNT FACTORY // string public constant AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK = "AF1"; string public constant AF_MINING_IS_FINISHED = "AF2"; string public constant AF_CREDIT_ACCOUNT_NOT_IN_STOCK = "AF3"; string public constant AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN = "AF4"; // // ADDRESS PROVIDER // string public constant AS_ADDRESS_NOT_FOUND = "AP1"; // // CONTRACTS REGISTER // string public constant CR_POOL_ALREADY_ADDED = "CR1"; string public constant CR_CREDIT_MANAGER_ALREADY_ADDED = "CR2"; // // CREDIT_FILTER // string public constant CF_UNDERLYING_TOKEN_FILTER_CONFLICT = "CF0"; string public constant CF_INCORRECT_LIQUIDATION_THRESHOLD = "CF1"; string public constant CF_TOKEN_IS_NOT_ALLOWED = "CF2"; string public constant CF_CREDIT_MANAGERS_ONLY = "CF3"; string public constant CF_ADAPTERS_ONLY = "CF4"; string public constant CF_OPERATION_LOW_HEALTH_FACTOR = "CF5"; string public constant CF_TOO_MUCH_ALLOWED_TOKENS = "CF6"; string public constant CF_INCORRECT_CHI_THRESHOLD = "CF7"; string public constant CF_INCORRECT_FAST_CHECK = "CF8"; string public constant CF_NON_TOKEN_CONTRACT = "CF9"; string public constant CF_CONTRACT_IS_NOT_IN_ALLOWED_LIST = "CFA"; string public constant CF_FAST_CHECK_NOT_COVERED_COLLATERAL_DROP = "CFB"; string public constant CF_SOME_LIQUIDATION_THRESHOLD_MORE_THAN_NEW_ONE = "CFC"; string public constant CF_ADAPTER_CAN_BE_USED_ONLY_ONCE = "CFD"; string public constant CF_INCORRECT_PRICEFEED = "CFE"; string public constant CF_TRANSFER_IS_NOT_ALLOWED = "CFF"; string public constant CF_CREDIT_MANAGER_IS_ALREADY_SET = "CFG"; // // CREDIT ACCOUNT // string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1"; string public constant CA_FACTORY_ONLY = "CA2"; // // PRICE ORACLE // string public constant PO_PRICE_FEED_DOESNT_EXIST = "PO0"; string public constant PO_TOKENS_WITH_DECIMALS_MORE_18_ISNT_ALLOWED = "PO1"; string public constant PO_AGGREGATOR_DECIMALS_SHOULD_BE_18 = "PO2"; // // ACL // string public constant ACL_CALLER_NOT_PAUSABLE_ADMIN = "ACL1"; string public constant ACL_CALLER_NOT_CONFIGURATOR = "ACL2"; // // WETH GATEWAY // string public constant WG_DESTINATION_IS_NOT_WETH_COMPATIBLE = "WG1"; string public constant WG_RECEIVE_IS_NOT_ALLOWED = "WG2"; string public constant WG_NOT_ENOUGH_FUNDS = "WG3"; // // LEVERAGED ACTIONS // string public constant LA_INCORRECT_VALUE = "LA1"; string public constant LA_HAS_VALUE_WITH_TOKEN_TRANSFER = "LA2"; string public constant LA_UNKNOWN_SWAP_INTERFACE = "LA3"; string public constant LA_UNKNOWN_LP_INTERFACE = "LA4"; string public constant LA_LOWER_THAN_AMOUNT_MIN = "LA5"; string public constant LA_TOKEN_OUT_IS_NOT_COLLATERAL = "LA6"; // // YEARN PRICE FEED // string public constant YPF_PRICE_PER_SHARE_OUT_OF_RANGE = "YP1"; string public constant YPF_INCORRECT_LIMITER_PARAMETERS = "YP2"; // // TOKEN DISTRIBUTOR // string public constant TD_WALLET_IS_ALREADY_CONNECTED_TO_VC = "TD1"; string public constant TD_INCORRECT_WEIGHTS = "TD2"; string public constant TD_NON_ZERO_BALANCE_AFTER_DISTRIBUTION = "TD3"; string public constant TD_CONTRIBUTOR_IS_NOT_REGISTERED = "TD4"; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Optimised for front-end Address Provider interface interface IAppAddressProvider { function getDataCompressor() external view returns (address); function getGearToken() external view returns (address); function getWethToken() external view returns (address); function getWETHGateway() external view returns (address); function getPriceOracle() external view returns (address); function getLeveragedActions() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {AddressProvider} from "./AddressProvider.sol"; import {ACL} from "./ACL.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title ACL Trait /// @notice Trait which adds acl functions to contract abstract contract ACLTrait is Pausable { // ACL contract to check rights ACL private _acl; /// @dev constructor /// @param addressProvider Address of address repository constructor(address addressProvider) { require( addressProvider != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); _acl = ACL(AddressProvider(addressProvider).getACL()); } /// @dev Reverts if msg.sender is not configurator modifier configuratorOnly() { require( _acl.isConfigurator(msg.sender), Errors.ACL_CALLER_NOT_CONFIGURATOR ); // T:[ACLT-8] _; } ///@dev Pause contract function pause() external { require( _acl.isPausableAdmin(msg.sender), Errors.ACL_CALLER_NOT_PAUSABLE_ADMIN ); // T:[ACLT-1] _pause(); } /// @dev Unpause contract function unpause() external { require( _acl.isUnpausableAdmin(msg.sender), Errors.ACL_CALLER_NOT_PAUSABLE_ADMIN ); // T:[ACLT-1],[ACLT-2] _unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract 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 () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title ACL keeps admins addresses /// More info: https://dev.gearbox.fi/security/roles contract ACL is Ownable { mapping(address => bool) public pausableAdminSet; mapping(address => bool) public unpausableAdminSet; // Contract version uint256 public constant version = 1; // emits each time when new pausable admin added event PausableAdminAdded(address indexed newAdmin); // emits each time when pausable admin removed event PausableAdminRemoved(address indexed admin); // emits each time when new unpausable admin added event UnpausableAdminAdded(address indexed newAdmin); // emits each times when unpausable admin removed event UnpausableAdminRemoved(address indexed admin); /// @dev Adds pausable admin address /// @param newAdmin Address of new pausable admin function addPausableAdmin(address newAdmin) external onlyOwner // T:[ACL-1] { pausableAdminSet[newAdmin] = true; // T:[ACL-2] emit PausableAdminAdded(newAdmin); // T:[ACL-2] } /// @dev Removes pausable admin /// @param admin Address of admin which should be removed function removePausableAdmin(address admin) external onlyOwner // T:[ACL-1] { pausableAdminSet[admin] = false; // T:[ACL-3] emit PausableAdminRemoved(admin); // T:[ACL-3] } /// @dev Returns true if the address is pausable admin and false if not function isPausableAdmin(address addr) external view returns (bool) { return pausableAdminSet[addr]; // T:[ACL-2,3] } /// @dev Adds unpausable admin address to the list /// @param newAdmin Address of new unpausable admin function addUnpausableAdmin(address newAdmin) external onlyOwner // T:[ACL-1] { unpausableAdminSet[newAdmin] = true; // T:[ACL-4] emit UnpausableAdminAdded(newAdmin); // T:[ACL-4] } /// @dev Removes unpausable admin /// @param admin Address of admin to be removed function removeUnpausableAdmin(address admin) external onlyOwner // T:[ACL-1] { unpausableAdminSet[admin] = false; // T:[ACL-5] emit UnpausableAdminRemoved(admin); // T:[ACL-5] } /// @dev Returns true if the address is unpausable admin and false if not function isUnpausableAdmin(address addr) external view returns (bool) { return unpausableAdminSet[addr]; // T:[ACL-4,5] } /// @dev Returns true if addr has configurator rights function isConfigurator(address account) external view returns (bool) { return account == owner(); // T:[ACL-6] } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {DataTypes} from "../../libraries/data/Types.sol"; /// @title Optimised for front-end credit Manager interface /// @notice It's optimised for light-weight abi interface IAppCreditManager { function openCreditAccount( uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external; function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths) external; function repayCreditAccount(address to) external; function increaseBorrowedAmount(uint256 amount) external; function addCollateral( address onBehalfOf, address token, uint256 amount ) external; function calcRepayAmount(address borrower, bool isLiquidated) external view returns (uint256); function getCreditAccountOrRevert(address borrower) external view returns (address); function hasOpenedCreditAccount(address borrower) external view returns (bool); function defaultSwapContract() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title DataType library /// @notice Contains data types used in data compressor. library DataTypes { struct Exchange { address[] path; uint256 amountOutMin; } struct TokenBalance { address token; uint256 balance; bool isAllowed; } struct ContractAdapter { address allowedContract; address adapter; } struct CreditAccountData { address addr; address borrower; bool inUse; address creditManager; address underlyingToken; uint256 borrowedAmountPlusInterest; uint256 totalValue; uint256 healthFactor; uint256 borrowRate; TokenBalance[] balances; } struct CreditAccountDataExtended { address addr; address borrower; bool inUse; address creditManager; address underlyingToken; uint256 borrowedAmountPlusInterest; uint256 totalValue; uint256 healthFactor; uint256 borrowRate; TokenBalance[] balances; uint256 repayAmount; uint256 liquidationAmount; bool canBeClosed; uint256 borrowedAmount; uint256 cumulativeIndexAtOpen; uint256 since; } struct CreditManagerData { address addr; bool hasAccount; address underlyingToken; bool isWETH; bool canBorrow; uint256 borrowRate; uint256 minAmount; uint256 maxAmount; uint256 maxLeverageFactor; uint256 availableLiquidity; address[] allowedTokens; ContractAdapter[] adapters; } struct PoolData { address addr; bool isWETH; address underlyingToken; address dieselToken; uint256 linearCumulativeIndex; uint256 availableLiquidity; uint256 expectedLiquidity; uint256 expectedLiquidityLimit; uint256 totalBorrowed; uint256 depositAPY_RAY; uint256 borrowAPY_RAY; uint256 dieselRate_RAY; uint256 withdrawFee; uint256 cumulativeIndex_RAY; uint256 timestampLU; } struct TokenInfo { address addr; string symbol; uint8 decimals; } struct AddressProviderData { address contractRegister; address acl; address priceOracle; address traderAccountFactory; address dataCompressor; address farmingFactory; address accountMiner; address treasuryContract; address gearToken; address wethToken; address wethGateway; } struct MiningApproval { address token; address swapContract; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external view returns (address); function WETH() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external view returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ICreditAccount} from "../interfaces/ICreditAccount.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title Credit Account /// @notice Implements generic credit account logic: /// - Keeps token balances /// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized /// - Approves tokens for 3rd party contracts /// - Transfers assets /// - Execute financial orders /// /// More: https://dev.gearbox.fi/developers/credit/credit_account contract CreditAccount is ICreditAccount, Initializable { using SafeERC20 for IERC20; using Address for address; address public override factory; // Keeps address of current credit Manager address public override creditManager; // Amount borrowed to this account uint256 public override borrowedAmount; // Cumulative index at credit account opening uint256 public override cumulativeIndexAtOpen; // Block number when it was initialised last time uint256 public override since; // Contract version uint constant public version = 1; /// @dev Restricts operation for current credit manager only modifier creditManagerOnly { require(msg.sender == creditManager, Errors.CA_CONNECTED_CREDIT_MANAGER_ONLY); _; } /// @dev Initialise used instead of constructor cause we use contract cloning function initialize() external override initializer { factory = msg.sender; } /// @dev Connects credit account to credit account address. Restricted to account factory (owner) only /// @param _creditManager Credit manager address function connectTo( address _creditManager, uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external override { require(msg.sender == factory, Errors.CA_FACTORY_ONLY); creditManager = _creditManager; // T:[CA-7] borrowedAmount = _borrowedAmount; // T:[CA-3,7] cumulativeIndexAtOpen = _cumulativeIndexAtOpen; // T:[CA-3,7] since = block.number; // T:[CA-7] } /// @dev Updates borrowed amount. Restricted for current credit manager only /// @param _borrowedAmount Amount which pool lent to credit account function updateParameters(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen) external override creditManagerOnly // T:[CA-2] { borrowedAmount = _borrowedAmount; // T:[CA-4] cumulativeIndexAtOpen = _cumulativeIndexAtOpen; } /// @dev Approves token for 3rd party contract. Restricted for current credit manager only /// @param token ERC20 token for allowance /// @param swapContract Swap contract address function approveToken(address token, address swapContract) external override creditManagerOnly // T:[CA-2] { IERC20(token).safeApprove(swapContract, 0); // T:[CA-5] IERC20(token).safeApprove(swapContract, Constants.MAX_INT); // T:[CA-5] } /// @dev Removes allowance token for 3rd party contract. Restricted for factory only /// @param token ERC20 token for allowance /// @param targetContract Swap contract address function cancelAllowance(address token, address targetContract) external override { require(msg.sender == factory, Errors.CA_FACTORY_ONLY); IERC20(token).safeApprove(targetContract, 0); } /// @dev Transfers tokens from credit account to provided address. Restricted for current credit manager only /// @param token Token which should be transferred from credit account /// @param to Address of recipient /// @param amount Amount to be transferred function safeTransfer( address token, address to, uint256 amount ) external override creditManagerOnly // T:[CA-2] { IERC20(token).safeTransfer(to, amount); // T:[CA-6] } /// @dev Executes financial order on 3rd party service. Restricted for current credit manager only /// @param destination Contract address which should be called /// @param data Call data which should be sent function execute(address destination, bytes memory data) external override creditManagerOnly returns (bytes memory) { return destination.functionCall(data); // T: [CM-48] } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {PercentageMath} from "../libraries/math/PercentageMath.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IAccountFactory} from "../interfaces/IAccountFactory.sol"; import {ICreditAccount} from "../interfaces/ICreditAccount.sol"; import {IPoolService} from "../interfaces/IPoolService.sol"; import {IWETHGateway} from "../interfaces/IWETHGateway.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {AddressProvider} from "../core/AddressProvider.sol"; import {ACLTrait} from "../core/ACLTrait.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {DataTypes} from "../libraries/data/Types.sol"; /// @title Credit Manager /// @notice It encapsulates business logic for managing credit accounts /// /// More info: https://dev.gearbox.fi/developers/credit/credit_manager /// /// #define roughEq(uint256 a, uint256 b) bool = /// a == b || a + 1 == b || a == b + 1; /// /// #define borrowedPlusInterest(address creditAccount) uint = /// let borrowedAmount, cumIndexAtOpen := getCreditAccountParameters(creditAccount) in /// let curCumulativeIndex := IPoolService(poolService).calcLinearCumulative_RAY() in /// borrowedAmount.mul(curCumulativeIndex).div(cumIndexAtOpen); contract CreditManager is ICreditManager, ACLTrait, ReentrancyGuard { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using Address for address payable; // Minimal amount for open credit account uint256 public override minAmount; // Maximum amount for open credit account uint256 public override maxAmount; // Maximum leveraged factor allowed for this pool uint256 public override maxLeverageFactor; // Minimal allowed Hf after increasing borrow amount uint256 public override minHealthFactor; // Mapping between borrowers'/farmers' address and credit account mapping(address => address) public override creditAccounts; // Account manager - provides credit accounts to pool IAccountFactory internal _accountFactory; // Credit Manager filter ICreditFilter public override creditFilter; // Underlying token address address public override underlyingToken; // Address of connected pool address public override poolService; // Address of WETH token address public wethAddress; // Address of WETH Gateway address public wethGateway; // Default swap contracts - uses for automatic close address public override defaultSwapContract; uint256 public override feeInterest; uint256 public override feeLiquidation; uint256 public override liquidationDiscount; // Contract version uint constant public version = 1; // // MODIFIERS // /// @dev Restricts actions for users with opened credit accounts only modifier allowedAdaptersOnly(address targetContract) { require( creditFilter.contractToAdapter(targetContract) == msg.sender, Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED ); _; } /// @dev Constructor /// @param _addressProvider Address Repository for upgradable contract model /// @param _minAmount Minimal amount for open credit account /// @param _maxAmount Maximum amount for open credit account /// @param _maxLeverage Maximum allowed leverage factor /// @param _poolService Address of pool service /// @param _creditFilterAddress CreditFilter address. It should be finalised /// @param _defaultSwapContract Default IUniswapV2Router02 contract to change assets in case of closing account constructor( address _addressProvider, uint256 _minAmount, uint256 _maxAmount, uint256 _maxLeverage, address _poolService, address _creditFilterAddress, address _defaultSwapContract ) ACLTrait(_addressProvider) { require( _addressProvider != address(0) && _poolService != address(0) && _creditFilterAddress != address(0) && _defaultSwapContract != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); AddressProvider addressProvider = AddressProvider(_addressProvider); // T:[CM-1] poolService = _poolService; // T:[CM-1] underlyingToken = IPoolService(_poolService).underlyingToken(); // T:[CM-1] wethAddress = addressProvider.getWethToken(); // T:[CM-1] wethGateway = addressProvider.getWETHGateway(); // T:[CM-1] defaultSwapContract = _defaultSwapContract; // T:[CM-1] _accountFactory = IAccountFactory(addressProvider.getAccountFactory()); // T:[CM-1] _setParams( _minAmount, _maxAmount, _maxLeverage, Constants.FEE_INTEREST, Constants.FEE_LIQUIDATION, Constants.LIQUIDATION_DISCOUNTED_SUM ); // T:[CM-1] creditFilter = ICreditFilter(_creditFilterAddress); // T:[CM-1] } // // CREDIT ACCOUNT MANAGEMENT // /** * @dev Opens credit account and provides credit funds. * - Opens credit account (take it from account factory^1) * - Transfers trader /farmers initial funds to credit account * - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract. * - Emits OpenCreditAccount event * Function reverts if user has already opened position * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account * * @param amount Borrowers own funds * @param onBehalfOf The address that we open credit account. Same as msg.sender if the user wants to open it for his own wallet, * or a different address if the beneficiary is a different wallet * @param leverageFactor Multiplier to borrowers own funds * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * * #if_succeeds {:msg "A credit account with the correct balance is opened."} * let newAccount := creditAccounts[onBehalfOf] in * newAccount != address(0) && * IERC20(underlyingToken).balanceOf(newAccount) >= * amount.add(amount.mul(leverageFactor).div(Constants.LEVERAGE_DECIMALS)); * * #if_succeeds {:msg "Sender looses amount tokens." } * IERC20(underlyingToken).balanceOf(msg.sender) == old(IERC20(underlyingToken).balanceOf(msg.sender)) - amount; * * #if_succeeds {:msg "Pool provides correct leverage (amount x leverageFactor)." } * IERC20(underlyingToken).balanceOf(poolService) == old(IERC20(underlyingToken).balanceOf(poolService)) - amount.mul(leverageFactor).div(Constants.LEVERAGE_DECIMALS); * * #if_succeeds {:msg "The new account is healthy."} * creditFilter.calcCreditAccountHealthFactor(creditAccounts[onBehalfOf]) >= PercentageMath.PERCENTAGE_FACTOR; * * #if_succeeds {:msg "The new account has balance <= 1 for all tokens other than the underlying token."} * let newAccount := creditAccounts[onBehalfOf] in * forall (uint i in 1...creditFilter.allowedTokensCount()) * IERC20(creditFilter.allowedTokens(i)).balanceOf(newAccount) <= 1; */ function openCreditAccount( uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external override whenNotPaused // T:[CM-39] nonReentrant { // Checks that amount is in limits require( amount >= minAmount && amount <= maxAmount && leverageFactor > 0 && leverageFactor <= maxLeverageFactor, Errors.CM_INCORRECT_PARAMS ); // T:[CM-2] // Checks that user "onBehalfOf" has no opened accounts // require( // !hasOpenedCreditAccount(onBehalfOf) && onBehalfOf != address(0), // Errors.CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT // ); // T:[CM-3] _checkAccountTransfer(onBehalfOf); // borrowedAmount = amount * leverageFactor uint256 borrowedAmount = amount.mul(leverageFactor).div( Constants.LEVERAGE_DECIMALS ); // T:[CM-7] // Get Reusable Credit account creditAccount address creditAccount = _accountFactory.takeCreditAccount( borrowedAmount, IPoolService(poolService).calcLinearCumulative_RAY() ); // T:[CM-5] // Initializes enabled tokens for the account. Enabled tokens is a bit mask which // holds information which tokens were used by user creditFilter.initEnabledTokens(creditAccount); // T:[CM-5] // Transfer pool tokens to new credit account IPoolService(poolService).lendCreditAccount( borrowedAmount, creditAccount ); // T:[CM-7] // Transfer borrower own fund to credit account IERC20(underlyingToken).safeTransferFrom( msg.sender, creditAccount, amount ); // T:[CM-6] // link credit account address with borrower address creditAccounts[onBehalfOf] = creditAccount; // T:[CM-5] // emit new event emit OpenCreditAccount( msg.sender, onBehalfOf, creditAccount, amount, borrowedAmount, referralCode ); // T:[CM-8] } /** * @dev Closes credit account * - Swaps all assets to underlying one using default swap protocol * - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount * - Transfers remaining funds to the trader / farmer * - Closes the credit account and return it to account factory * - Emits CloseCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account * * @param to Address to send remaining funds * @param paths Exchange type data which provides paths + amountMinOut * * #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0); * #if_succeeds {:msg "Can only close healthy accounts" } old(creditFilter.calcCreditAccountHealthFactor(creditAccounts[msg.sender])) > PercentageMath.PERCENTAGE_FACTOR; * #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"} * let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[msg.sender])) in * IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool); */ function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // T: [CM-9, 44] // Converts all assets to underlying one. _convertAllAssetsToUnderlying is virtual _convertAllAssetsToUnderlying(creditAccount, paths); // T: [CM-44] // total value equals underlying assets after converting all assets uint256 totalValue = IERC20(underlyingToken).balanceOf(creditAccount); // T: [CM-44] (, uint256 remainingFunds) = _closeCreditAccountImpl( creditAccount, Constants.OPERATION_CLOSURE, totalValue, msg.sender, address(0), to ); // T: [CM-44] emit CloseCreditAccount(msg.sender, to, remainingFunds); // T: [CM-44] } /** * @dev Liquidates credit account * - Transfers discounted total credit account value from liquidators account * - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner * - Transfer all assets from credit account to liquidator ("to") account * - Returns credit account to factory * - Emits LiquidateCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account * * @param borrower Borrower address * @param to Address to transfer all assets from credit account * * #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0); * #if_succeeds {:msg "Can only liquidate an un-healthy accounts" } old(creditFilter.calcCreditAccountHealthFactor(creditAccounts[msg.sender])) < PercentageMath.PERCENTAGE_FACTOR; */ function liquidateCreditAccount( address borrower, address to, bool force ) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(borrower); // T: [CM-9] // transfers assets to "to" address and compute total value (tv) & threshold weighted value (twv) (uint256 totalValue, uint256 tvw) = _transferAssetsTo( creditAccount, to, force ); // T:[CM-13, 16, 17] // Checks that current Hf < 1 require( tvw < creditFilter .calcCreditAccountAccruedInterest(creditAccount) .mul(PercentageMath.PERCENTAGE_FACTOR), Errors.CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR ); // T:[CM-13, 16, 17] // Liquidate credit account (, uint256 remainingFunds) = _closeCreditAccountImpl( creditAccount, Constants.OPERATION_LIQUIDATION, totalValue, borrower, msg.sender, to ); // T:[CM-13] emit LiquidateCreditAccount(borrower, msg.sender, remainingFunds); // T:[CM-13] } /// @dev Repays credit account /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account /// /// @param to Address to send credit account assets /// #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0); /// #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"} /// let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[msg.sender])) in /// IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool); function repayCreditAccount(address to) external override whenNotPaused // T:[CM-39] nonReentrant { _repayCreditAccountImpl(msg.sender, to); // T:[CM-17] } /// @dev Repay credit account with ETH. Restricted to be called by WETH Gateway only /// /// @param borrower Address of borrower /// @param to Address to send credit account assets /// #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"} /// let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[borrower])) in /// IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool); function repayCreditAccountETH(address borrower, address to) external override whenNotPaused // T:[CM-39] nonReentrant returns (uint256) { // Checks that msg.sender is WETH Gateway require(msg.sender == wethGateway, Errors.CM_WETH_GATEWAY_ONLY); // T:[CM-38] // Difference with usual Repay is that there is borrower in repay implementation call return _repayCreditAccountImpl(borrower, to); // T:[WG-11] } /// @dev Implements logic for repay credit accounts /// /// @param borrower Borrower address /// @param to Address to transfer assets from credit account function _repayCreditAccountImpl(address borrower, address to) internal returns (uint256) { address creditAccount = getCreditAccountOrRevert(borrower); (uint256 totalValue, ) = _transferAssetsTo(creditAccount, to, false); // T:[CM-17, 23] (uint256 amountToPool, ) = _closeCreditAccountImpl( creditAccount, Constants.OPERATION_REPAY, totalValue, borrower, borrower, to ); // T:[CM-17] emit RepayCreditAccount(borrower, to); // T:[CM-18] return amountToPool; } /// @dev Implementation for all closing account procedures /// #if_succeeds {:msg "Credit account balances should be <= 1 for all allowed tokens after closing"} /// forall (uint i in 0...creditFilter.allowedTokensCount()) /// IERC20(creditFilter.allowedTokens(i)).balanceOf(creditAccount) <= 1; function _closeCreditAccountImpl( address creditAccount, uint8 operation, uint256 totalValue, address borrower, address liquidator, address to ) internal returns (uint256, uint256) { bool isLiquidated = operation == Constants.OPERATION_LIQUIDATION; ( uint256 borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss ) = _calcClosePayments(creditAccount, totalValue, isLiquidated); // T:[CM-11, 15, 17] if (operation == Constants.OPERATION_CLOSURE) { ICreditAccount(creditAccount).safeTransfer( underlyingToken, poolService, amountToPool ); // T:[CM-11] // close operation with loss is not allowed require(remainingFunds > 0, Errors.CM_CANT_CLOSE_WITH_LOSS); // T:[CM-42] // transfer remaining funds to borrower _safeTokenTransfer( creditAccount, underlyingToken, to, remainingFunds, false ); // T:[CM-11] } // LIQUIDATION else if (operation == Constants.OPERATION_LIQUIDATION) { // repay amount to pool IERC20(underlyingToken).safeTransferFrom( liquidator, poolService, amountToPool ); // T:[CM-14] // transfer remaining funds to borrower if (remainingFunds > 0) { IERC20(underlyingToken).safeTransferFrom( liquidator, borrower, remainingFunds ); //T:[CM-14] } } // REPAY else { // repay amount to pool IERC20(underlyingToken).safeTransferFrom( msg.sender, // msg.sender in case of WETH Gateway poolService, amountToPool ); // T:[CM-17] } // Return creditAccount _accountFactory.returnCreditAccount(creditAccount); // T:[CM-21] // Release memory delete creditAccounts[borrower]; // T:[CM-27] // Transfer pool tokens to new credit account IPoolService(poolService).repayCreditAccount( borrowedAmount, profit, loss ); // T:[CM-11, 15] return (amountToPool, remainingFunds); // T:[CM-11] } /// @dev Collects data and call calc payments pure function during closure procedures /// @param creditAccount Credit account address /// @param totalValue Credit account total value /// @param isLiquidated True if calculations needed for liquidation function _calcClosePayments( address creditAccount, uint256 totalValue, bool isLiquidated ) public view returns ( uint256 _borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss ) { // Gets credit account parameters ( uint256 borrowedAmount, uint256 cumulativeIndexAtCreditAccountOpen_RAY ) = getCreditAccountParameters(creditAccount); // T:[CM-13] return _calcClosePaymentsPure( totalValue, isLiquidated, borrowedAmount, cumulativeIndexAtCreditAccountOpen_RAY, IPoolService(poolService).calcLinearCumulative_RAY() ); } /// @dev Computes all close parameters based on data /// @param totalValue Credit account total value /// @param isLiquidated True if calculations needed for liquidation /// @param borrowedAmount Credit account borrow amount /// @param cumulativeIndexAtCreditAccountOpen_RAY Cumulative index at opening credit account in RAY format /// @param cumulativeIndexNow_RAY Current value of cumulative index in RAY format function _calcClosePaymentsPure( uint256 totalValue, bool isLiquidated, uint256 borrowedAmount, uint256 cumulativeIndexAtCreditAccountOpen_RAY, uint256 cumulativeIndexNow_RAY ) public view returns ( uint256 _borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss ) { uint256 totalFunds = isLiquidated ? totalValue.mul(liquidationDiscount).div( PercentageMath.PERCENTAGE_FACTOR ) : totalValue; // T:[CM-45] _borrowedAmount = borrowedAmount; // T:[CM-45] uint256 borrowedAmountWithInterest = borrowedAmount .mul(cumulativeIndexNow_RAY) .div(cumulativeIndexAtCreditAccountOpen_RAY); // T:[CM-45] if (totalFunds < borrowedAmountWithInterest) { amountToPool = totalFunds.sub(1); // T:[CM-45] loss = borrowedAmountWithInterest.sub(amountToPool); // T:[CM-45] } else { amountToPool = isLiquidated ? totalFunds.percentMul(feeLiquidation).add( borrowedAmountWithInterest ) : borrowedAmountWithInterest.add( borrowedAmountWithInterest.sub(borrowedAmount).percentMul( feeInterest ) ); // T:[CM-45] if (totalFunds > amountToPool) { remainingFunds = totalFunds.sub(amountToPool).sub(1); // T:[CM-45] } else { amountToPool = totalFunds.sub(1); // T:[CM-45] } profit = amountToPool.sub(borrowedAmountWithInterest); // T:[CM-45] } } /// @dev Transfers all assets from borrower credit account to "to" account and converts WETH => ETH if applicable /// @param creditAccount Credit account address /// @param to Address to transfer all assets to function _transferAssetsTo( address creditAccount, address to, bool force ) internal returns (uint256 totalValue, uint256 totalWeightedValue) { uint256 tokenMask; uint256 enabledTokens = creditFilter.enabledTokens(creditAccount); require(to != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED); for (uint256 i = 0; i < creditFilter.allowedTokensCount(); i++) { tokenMask = 1 << i; if (enabledTokens & tokenMask > 0) { ( address token, uint256 amount, uint256 tv, uint256 tvw ) = creditFilter.getCreditAccountTokenById(creditAccount, i); // T:[CM-14, 17, 22, 23] if (amount > 1) { if ( _safeTokenTransfer( creditAccount, token, to, amount.sub(1), // Michael Egorov gas efficiency trick force ) ) { totalValue = totalValue.add(tv); // T:[CM-14, 17, 22, 23] totalWeightedValue = totalWeightedValue.add(tvw); // T:[CM-14, 17, 22, 23] } } } } } /// @dev Transfers token to particular address from credit account and converts WETH => ETH if applicable /// @param creditAccount Address of credit account /// @param token Token address /// @param to Address to transfer asset /// @param amount Amount to be transferred /// @param force If true it will skip reverts of safeTransfer function. Used for force liquidation if there is /// a blocked token on creditAccount /// @return true if transfer were successful otherwise false function _safeTokenTransfer( address creditAccount, address token, address to, uint256 amount, bool force ) internal returns (bool) { if (token != wethAddress) { try ICreditAccount(creditAccount).safeTransfer(token, to, amount) // T:[CM-14, 17] {} catch { require(force, Errors.CM_TRANSFER_FAILED); // T:[CM-50] return false; } } else { ICreditAccount(creditAccount).safeTransfer( token, wethGateway, amount ); // T:[CM-22, 23] IWETHGateway(wethGateway).unwrapWETH(to, amount); // T:[CM-22, 23] } return true; } /// @dev Increases borrowed amount by transferring additional funds from /// the pool if after that HealthFactor > minHealth /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount /// /// @param amount Amount to increase borrowed amount function increaseBorrowedAmount(uint256 amount) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // T: [CM-9, 30] ( uint256 borrowedAmount, uint256 cumulativeIndexAtOpen ) = getCreditAccountParameters(creditAccount); // T:[CM-30] // uint256 newBorrowedAmount = borrowedAmount.add(amount); uint256 newCumulativeIndex = IPoolService(poolService) .calcCumulativeIndexAtBorrowMore( borrowedAmount, amount, cumulativeIndexAtOpen ); // T:[CM-30] require( newBorrowedAmount.mul(Constants.LEVERAGE_DECIMALS) < maxAmount.mul(maxLeverageFactor), Errors.CM_INCORRECT_AMOUNT ); // T:[CM-51] // // Increase _totalBorrowed, it used to compute forecasted interest IPoolService(poolService).lendCreditAccount(amount, creditAccount); // T:[CM-29] // // Set parameters for new credit account ICreditAccount(creditAccount).updateParameters( newBorrowedAmount, newCumulativeIndex ); // T:[CM-30] // creditFilter.revertIfCantIncreaseBorrowing( creditAccount, minHealthFactor ); // T:[CM-28] emit IncreaseBorrowedAmount(msg.sender, amount); // T:[CM-29] } /// @dev Adds collateral to borrower's credit account /// @param onBehalfOf Address of borrower to add funds /// @param token Token address /// @param amount Amount to add function addCollateral( address onBehalfOf, address token, uint256 amount ) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(onBehalfOf); // T: [CM-9] creditFilter.checkAndEnableToken(creditAccount, token); // T:[CM-48] IERC20(token).safeTransferFrom(msg.sender, creditAccount, amount); // T:[CM-48] emit AddCollateral(onBehalfOf, token, amount); // T: [CM-48] } /// @dev Sets fees. Restricted for configurator role only /// @param _minAmount Minimum amount to open account /// @param _maxAmount Maximum amount to open account /// @param _maxLeverageFactor Maximum leverage factor /// @param _feeInterest Interest fee multiplier /// @param _feeLiquidation Liquidation fee multiplier (for totalValue) /// @param _liquidationDiscount Liquidation premium multiplier (= PERCENTAGE_FACTOR - premium) function setParams( uint256 _minAmount, uint256 _maxAmount, uint256 _maxLeverageFactor, uint256 _feeInterest, uint256 _feeLiquidation, uint256 _liquidationDiscount ) public configuratorOnly // T:[CM-36] { _setParams( _minAmount, _maxAmount, _maxLeverageFactor, _feeInterest, _feeLiquidation, _liquidationDiscount ); } function _setParams( uint256 _minAmount, uint256 _maxAmount, uint256 _maxLeverageFactor, uint256 _feeInterest, uint256 _feeLiquidation, uint256 _liquidationDiscount ) internal { require( _minAmount <= _maxAmount && _maxLeverageFactor > 0, Errors.CM_INCORRECT_PARAMS ); // T:[CM-34] minAmount = _minAmount; // T:[CM-32] maxAmount = _maxAmount; // T:[CM-32] maxLeverageFactor = _maxLeverageFactor; feeInterest = _feeInterest; // T:[CM-37] feeLiquidation = _feeLiquidation; // T:[CM-37] liquidationDiscount = _liquidationDiscount; // T:[CM-37] // Compute minHealthFactor: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrow-amount // LT_U = liquidationDiscount - feeLiquidation minHealthFactor = liquidationDiscount .sub(feeLiquidation) .mul(maxLeverageFactor.add(Constants.LEVERAGE_DECIMALS)) .div(maxLeverageFactor); // T:[CM-41] if (address(creditFilter) != address(0)) { creditFilter.updateUnderlyingTokenLiquidationThreshold(); // T:[CM-49] } emit NewParameters( minAmount, maxAmount, maxLeverageFactor, feeInterest, feeLiquidation, liquidationDiscount ); // T:[CM-37] } /// @dev Approves credit account for 3rd party contract /// @param targetContract Contract to check allowance /// @param token Token address of contract function approve(address targetContract, address token) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // Checks that targetContract is allowed - it has non-zero address adapter require( creditFilter.contractToAdapter(targetContract) != address(0), Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED ); creditFilter.revertIfTokenNotAllowed(token); // ToDo: add test _provideCreditAccountAllowance(creditAccount, targetContract, token); } /// @dev Approve tokens for credit accounts. Restricted for adapters only /// @param creditAccount Credit account address /// @param targetContract Contract to check allowance /// @param token Token address of contract function provideCreditAccountAllowance( address creditAccount, address targetContract, address token ) external override allowedAdaptersOnly(targetContract) // T:[CM-46] whenNotPaused // T:[CM-39] nonReentrant { _provideCreditAccountAllowance(creditAccount, targetContract, token); // T:[CM-35] } /// @dev Checks that credit account has enough allowance for operation by comparing existing one with x10 times more than needed /// @param creditAccount Credit account address /// @param toContract Contract to check allowance /// @param token Token address of contract function _provideCreditAccountAllowance( address creditAccount, address toContract, address token ) internal { // Get 10x reserve in allowance if ( IERC20(token).allowance(creditAccount, toContract) < Constants.MAX_INT_4 ) { ICreditAccount(creditAccount).approveToken(token, toContract); // T:[CM-35] } } /// @dev Converts all assets to underlying one using uniswap V2 protocol /// @param creditAccount Credit Account address /// @param paths Exchange type data which provides paths + amountMinOut function _convertAllAssetsToUnderlying( address creditAccount, DataTypes.Exchange[] calldata paths ) internal { uint256 tokenMask; uint256 enabledTokens = creditFilter.enabledTokens(creditAccount); // T: [CM-44] require( paths.length == creditFilter.allowedTokensCount(), Errors.INCORRECT_PATH_LENGTH ); // ToDo: check for (uint256 i = 1; i < paths.length; i++) { tokenMask = 1 << i; if (enabledTokens & tokenMask > 0) { (address tokenAddr, uint256 amount, , ) = creditFilter .getCreditAccountTokenById(creditAccount, i); // T: [CM-44] if (amount > 1) { _provideCreditAccountAllowance( creditAccount, defaultSwapContract, tokenAddr ); // T: [CM-44] address[] memory currentPath = paths[i].path; currentPath[0] = tokenAddr; currentPath[paths[i].path.length - 1] = underlyingToken; bytes memory data = abi.encodeWithSelector( bytes4(0x38ed1739), // "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)", amount.sub(1), paths[i].amountOutMin, // T: [CM-45] currentPath, creditAccount, block.timestamp ); // T: [CM-44] ICreditAccount(creditAccount).execute( defaultSwapContract, data ); // T: [CM-44] } } } } /// @dev Executes filtered order on credit account which is connected with particular borrower /// @param borrower Borrower address /// @param target Target smart-contract /// @param data Call data for call function executeOrder( address borrower, address target, bytes memory data ) external override allowedAdaptersOnly(target) // T:[CM-46] whenNotPaused // T:[CM-39] nonReentrant returns (bytes memory) { address creditAccount = getCreditAccountOrRevert(borrower); // T:[CM-9] emit ExecuteOrder(borrower, target); return ICreditAccount(creditAccount).execute(target, data); // : [CM-47] } // // GETTERS // /// @dev Returns true if the borrower has opened a credit account /// @param borrower Borrower account function hasOpenedCreditAccount(address borrower) public view override returns (bool) { return creditAccounts[borrower] != address(0); // T:[CM-26] } /// @dev Returns address of borrower's credit account and reverts of borrower has no one. /// @param borrower Borrower address function getCreditAccountOrRevert(address borrower) public view override returns (address) { address result = creditAccounts[borrower]; // T: [CM-9] require(result != address(0), Errors.CM_NO_OPEN_ACCOUNT); // T: [CM-9] return result; } /// @dev Calculates repay / liquidation amount /// repay amount = borrow amount + interest accrued + fee amount /// /// More info: https://dev.gearbox.fi/developers/credit/economy#repay /// https://dev.gearbox.fi/developers/credit/economy#liquidate /// @param borrower Borrower address /// @param isLiquidated True if calculated repay amount for liquidator function calcRepayAmount(address borrower, bool isLiquidated) external view override returns (uint256) { address creditAccount = getCreditAccountOrRevert(borrower); uint256 totalValue = creditFilter.calcTotalValue(creditAccount); ( , uint256 amountToPool, uint256 remainingFunds, , ) = _calcClosePayments(creditAccount, totalValue, isLiquidated); // T:[CM-14, 17, 31] return isLiquidated ? amountToPool.add(remainingFunds) : amountToPool; // T:[CM-14, 17, 31] } /// @dev Gets credit account generic parameters /// @param creditAccount Credit account address /// @return borrowedAmount Amount which pool lent to credit account /// @return cumulativeIndexAtOpen Cumulative index at open. Used for interest calculation function getCreditAccountParameters(address creditAccount) internal view returns (uint256 borrowedAmount, uint256 cumulativeIndexAtOpen) { borrowedAmount = ICreditAccount(creditAccount).borrowedAmount(); cumulativeIndexAtOpen = ICreditAccount(creditAccount) .cumulativeIndexAtOpen(); } /// @dev Transfers account ownership to another account /// @param newOwner Address of new owner function transferAccountOwnership(address newOwner) external override whenNotPaused // T: [CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // M:[LA-1,2,3,4,5,6,7,8] // T:[CM-52,53, 54] _checkAccountTransfer(newOwner); delete creditAccounts[msg.sender]; // T:[CM-54], M:[LA-1,2,3,4,5,6,7,8] creditAccounts[newOwner] = creditAccount; // T:[CM-54], M:[LA-1,2,3,4,5,6,7,8] emit TransferAccount(msg.sender, newOwner); // T:[CM-54] } function _checkAccountTransfer(address newOwner) internal view { require( newOwner != address(0) && !hasOpenedCreditAccount(newOwner), Errors.CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT ); // T:[CM-52,53] if (msg.sender != newOwner) { creditFilter.revertIfAccountTransferIsNotAllowed( msg.sender, newOwner ); // T:[54,55] } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Reusable Credit Account interface /// @notice Implements general credit account: /// - Keeps token balances /// - Keeps token balances /// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized /// - Approves tokens for 3rd party contracts /// - Transfers assets /// - Execute financial orders /// /// More: https://dev.gearbox.fi/developers/creditManager/vanillacreditAccount interface ICreditAccount { /// @dev Initializes clone contract function initialize() external; /// @dev Connects credit account to credit manager /// @param _creditManager Credit manager address function connectTo( address _creditManager, uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external; // /// @dev Set general credit account parameters. Restricted to credit managers only // /// @param _borrowedAmount Amount which pool lent to credit account // /// @param _cumulativeIndexAtOpen Cumulative index at open. Uses for interest calculation // function setGenericParameters( // // ) external; /// @dev Updates borrowed amount. Restricted to credit managers only /// @param _borrowedAmount Amount which pool lent to credit account function updateParameters( uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external; /// @dev Approves particular token for swap contract /// @param token ERC20 token for allowance /// @param swapContract Swap contract address function approveToken(address token, address swapContract) external; /// @dev Cancels allowance for particular contract /// @param token Address of token for allowance /// @param targetContract Address of contract to cancel allowance function cancelAllowance(address token, address targetContract) external; /// Transfers tokens from credit account to provided address. Restricted for pool calls only /// @param token Token which should be tranferred from credit account /// @param to Address of recipient /// @param amount Amount to be transferred function safeTransfer( address token, address to, uint256 amount ) external; /// @dev Returns borrowed amount function borrowedAmount() external view returns (uint256); /// @dev Returns cumulative index at time of opening credit account function cumulativeIndexAtOpen() external view returns (uint256); /// @dev Returns Block number when it was initialised last time function since() external view returns (uint256); /// @dev Address of last connected credit manager function creditManager() external view returns (address); /// @dev Address of last connected credit manager function factory() external view returns (address); /// @dev Executed financial order on 3rd party service. Restricted for pool calls only /// @param destination Contract address which should be called /// @param data Call data which should be sent function execute(address destination, bytes memory data) external returns (bytes memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.7.4; import {Errors} from "../helpers/Errors.sol"; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; // T:[PM-1] } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[PM-1] return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; // T:[PM-1] } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[PM-2] uint256 halfPercentage = percentage / 2; // T:[PM-2] require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[PM-2] return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {DataTypes} from "../libraries/data/Types.sol"; interface IAccountFactory { // emits if new account miner was changed event AccountMinerChanged(address indexed miner); // emits each time when creditManager takes credit account event NewCreditAccount(address indexed account); // emits each time when creditManager takes credit account event InitializeCreditAccount( address indexed account, address indexed creditManager ); // emits each time when pool returns credit account event ReturnCreditAccount(address indexed account); // emits each time when DAO takes account from account factory forever event TakeForever(address indexed creditAccount, address indexed to); /// @dev Provide new creditAccount to pool. Creates a new one, if needed /// @return Address of creditAccount function takeCreditAccount( uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external returns (address); /// @dev Takes credit account back and stay in tn the queue /// @param usedAccount Address of used credit account function returnCreditAccount(address usedAccount) external; /// @dev Returns address of next available creditAccount function getNext(address creditAccount) external view returns (address); /// @dev Returns head of list of unused credit accounts function head() external view returns (address); /// @dev Returns tail of list of unused credit accounts function tail() external view returns (address); /// @dev Returns quantity of unused credit accounts in the stock function countCreditAccountsInStock() external view returns (uint256); /// @dev Returns credit account address by its id function creditAccounts(uint256 id) external view returns (address); /// @dev Quantity of credit accounts function countCreditAccounts() external view returns (uint256); // function miningApprovals(uint i) external returns(DataTypes.MiningApproval calldata); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {IAppPoolService} from "./app/IAppPoolService.sol"; /// @title Pool Service Interface /// @notice Implements business logic: /// - Adding/removing pool liquidity /// - Managing diesel tokens & diesel rates /// - Lending/repaying funds to credit Manager /// More: https://dev.gearbox.fi/developers/pool/abstractpoolservice interface IPoolService is IAppPoolService { // Emits each time when LP adds liquidity to the pool event AddLiquidity( address indexed sender, address indexed onBehalfOf, uint256 amount, uint256 referralCode ); // Emits each time when LP removes liquidity to the pool event RemoveLiquidity( address indexed sender, address indexed to, uint256 amount ); // Emits each time when Credit Manager borrows money from pool event Borrow( address indexed creditManager, address indexed creditAccount, uint256 amount ); // Emits each time when Credit Manager repays money from pool event Repay( address indexed creditManager, uint256 borrowedAmount, uint256 profit, uint256 loss ); // Emits each time when Interest Rate model was changed event NewInterestRateModel(address indexed newInterestRateModel); // Emits each time when new credit Manager was connected event NewCreditManagerConnected(address indexed creditManager); // Emits each time when borrow forbidden for credit manager event BorrowForbidden(address indexed creditManager); // Emits each time when uncovered (non insured) loss accrued event UncoveredLoss(address indexed creditManager, uint256 loss); // Emits after expected liquidity limit update event NewExpectedLiquidityLimit(uint256 newLimit); // Emits each time when withdraw fee is udpated event NewWithdrawFee(uint256 fee); // // LIQUIDITY MANAGEMENT // /** * @dev Adds liquidity to pool * - transfers lp tokens to pool * - mint diesel (LP) tokens and provide them * @param amount Amount of tokens to be transfer * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function addLiquidity( uint256 amount, address onBehalfOf, uint256 referralCode ) external override; /** * @dev Removes liquidity from pool * - burns lp's diesel (LP) tokens * - returns underlying tokens to lp * @param amount Amount of tokens to be transfer * @param to Address to transfer liquidity */ function removeLiquidity(uint256 amount, address to) external override returns (uint256); /** * @dev Transfers money from the pool to credit account * and updates the pool parameters * @param borrowedAmount Borrowed amount for credit account * @param creditAccount Credit account address */ function lendCreditAccount(uint256 borrowedAmount, address creditAccount) external; /** * @dev Recalculates total borrowed & borrowRate * mints/burns diesel tokens */ function repayCreditAccount( uint256 borrowedAmount, uint256 profit, uint256 loss ) external; // // GETTERS // /** * @return expected pool liquidity */ function expectedLiquidity() external view returns (uint256); /** * @return expected liquidity limit */ function expectedLiquidityLimit() external view returns (uint256); /** * @dev Gets available liquidity in the pool (pool balance) * @return available pool liquidity */ function availableLiquidity() external view returns (uint256); /** * @dev Calculates interest accrued from the last update using the linear model */ function calcLinearCumulative_RAY() external view returns (uint256); /** * @dev Calculates borrow rate * @return borrow rate in RAY format */ function borrowAPY_RAY() external view returns (uint256); /** * @dev Gets the amount of total borrowed funds * @return Amount of borrowed funds at current time */ function totalBorrowed() external view returns (uint256); /** * @return Current diesel rate **/ function getDieselRate_RAY() external view returns (uint256); /** * @dev Underlying token address getter * @return address of underlying ERC-20 token */ function underlyingToken() external view returns (address); /** * @dev Diesel(LP) token address getter * @return address of diesel(LP) ERC-20 token */ function dieselToken() external view returns (address); /** * @dev Credit Manager address getter * @return address of Credit Manager contract by id */ function creditManagers(uint256 id) external view returns (address); /** * @dev Credit Managers quantity * @return quantity of connected credit Managers */ function creditManagersCount() external view returns (uint256); function creditManagersCanBorrow(address id) external view returns (bool); function toDiesel(uint256 amount) external view returns (uint256); function fromDiesel(uint256 amount) external view returns (uint256); function withdrawFee() external view returns (uint256); function _timestampLU() external view returns (uint256); function _cumulativeIndex_RAY() external view returns (uint256); function calcCumulativeIndexAtBorrowMore( uint256 amount, uint256 dAmount, uint256 cumulativeIndexAtOpen ) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title POptimised for front-end Pool Service Interface interface IAppPoolService { function addLiquidity( uint256 amount, address onBehalfOf, uint256 referralCode ) external; function removeLiquidity(uint256 amount, address to) external returns(uint256); }
Deposit credit account tokens to Yearn amount in tokens bytes4(0xb6b55f25) = deposit
function deposit(uint256 amount) external override nonReentrant returns (uint256) { }
9,982,013
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ /** * @title CXIP Custom Bug Fix for the Justin Aversano - Smoke and Mirrors collection. * @author CXIP-Labs * @notice This is a custom bug fix for a very specific contract. * @dev Goal of this fix is to shift token data off by one, and fix the token id missmatch to titles. */ contract AversanoBugFix { /** * @dev Stores default collection data: name, symbol, and royalties. */ CollectionData private _collectionData; /** * @dev Internal last minted token id, to allow for auto-increment. */ uint256 private _currentTokenId; /** * @dev Array of all token ids in collection. */ uint256[] private _allTokens; /** * @dev Map of token id to array index of _ownedTokens. */ mapping(uint256 => uint256) private _ownedTokensIndex; /** * @dev Token id to wallet (owner) address map. */ mapping(uint256 => address) private _tokenOwner; /** * @dev 1-to-1 map of token id that was assigned an approved operator address. */ mapping(uint256 => address) private _tokenApprovals; /** * @dev Map of total tokens owner by a specific address. */ mapping(address => uint256) private _ownedTokensCount; /** * @dev Map of array of token ids owned by a specific address. */ mapping(address => uint256[]) private _ownedTokens; /** * @notice Map of full operator approval for a particular address. * @dev Usually utilised for supporting marketplace proxy wallets. */ mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Token data mapped by token id. */ mapping(uint256 => TokenData) private _tokenData; /** * @dev We are leaving constructor empty on purpose. To not disturb any existing data */ constructor() {} /** * @dev Shifting tokens back by one, from token #6 to token #79 * @dev This will result in #6 -> #5, and all the way to #79 -> #78 * @dev Token #79 will need to be burned after this */ function aversanoTokenIdMissmatchFix() public { require( ( msg.sender == 0x799E1Fe921d587D7C956e73E95fF6103DC3E7883 // Justin Aversano ETH wallet || msg.sender == 0xF76119Ba666fe838431544cDBA513dE9b6d851C1 // CXIP Gnosis Safe multisig ), "CXIP: Unauthorized wallet" ); require(address(this) == 0xE6501d00DDCa2AB22c655C612e73Ed822D9256a2, "CXIP: Unauthorized address"); for (uint256 i = 6; i < 80; i++) { _tokenData [i - 1] = _tokenData [i]; } } } struct CollectionData { bytes32 name; bytes32 name2; bytes32 symbol; address royalties; uint96 bps; } enum UriType { ARWEAVE, // 0 IPFS, // 1 HTTP // 2 } struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } struct Verification { bytes32 r; bytes32 s; uint8 v; }
Shifting tokens back by one, from token 6 to token 79 This will result in 6 -> 5, and all the way to 79 -> 78 Token 79 will need to be burned after this/
function aversanoTokenIdMissmatchFix() public { require( ( ), "CXIP: Unauthorized wallet" ); require(address(this) == 0xE6501d00DDCa2AB22c655C612e73Ed822D9256a2, "CXIP: Unauthorized address"); for (uint256 i = 6; i < 80; i++) { _tokenData [i - 1] = _tokenData [i]; } }
10,053,617
./full_match/1/0xCE37F9052E0f3f8E56887d8496FcD6cd6BeC06d0/sources/contracts/ColiseumSBT.sol
Mints tokens and assigns them to multiple addresses in one function call. targets An array of addresses to receive the minted tokens./
function airDrop(address[] calldata targets) external { require( (_controller[msg.sender] == true) || (owner() == _msgSender()), "Caller is not authorized" ); for (uint256 i = 0; i < targets.length; i++) { _mint(targets[i], 1); _tokenToTier[totalMinted()] = 2; } soulBoundedAmount += targets.length; }
4,953,101
./full_match/42/0xc1fe8dD660e10844dAC9407F08CcA9D7A687CfaD/sources/PromFans/PRBMathUD60x18.sol
Calculates geometric mean of x and y, i.e. sqrt(x y), rounding down. Requirements: - x y must fit within MAX_UD60x18, lest it overflows. x The first operand as an unsigned 60.18-decimal fixed-point number. y The second operand as an unsigned 60.18-decimal fixed-point number. return result The result as an unsigned 60.18-decimal fixed-point number. Checking for overflow this way is faster than letting Solidity do it. We don't need to multiply by the SCALE here because the xy product had already picked up a factor of SCALE during multiplication. See the comments within the "sqrt" function.
function gm(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { if (x.value == 0) { } unchecked { uint256 xy = x.value * y.value; require(xy / x.value == y.value); } }
9,579,099
./partial_match/1/0x55ce89Ff9dBf3208c95315aeaB9a1A3cF7242801/sources/MerkleDistributorVeSolid.sol
Verify the merkle proof. Mark it claimed and send the token. Split NFT Transfer NFT (intentionally use transferFrom instead of safeTransferFrom)
function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external override { require(!isClaimed(index), "MerkleDistributor: Drop already claimed."); require(msg.sender == account, "!account"); bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require( MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof." ); _setClaimed(index); uint256 tokenId = IVe(token).split(rootTokenId, amount); IVe(token).transferFrom(address(this), account, tokenId); emit Claimed(index, account, tokenId, amount); }
4,142,069
/** *Submitted for verification at Etherscan.io on 2021-08-11 */ // File: iface/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); /** * @dev 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: iface/IParassetGovernance.sol pragma solidity ^0.8.4; /// @dev This interface defines the governance methods interface IParassetGovernance { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File: ParassetBase.sol pragma solidity ^0.8.4; contract ParassetBase { // Lock flag uint256 _locked; /// @dev To support open-zeppelin/upgrades /// @param governance IParassetGovernance implementation contract address function initialize(address governance) public virtual { require(_governance == address(0), "Log:ParassetBase!initialize"); _governance = governance; _locked = 0; } /// @dev IParassetGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance IParassetGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || IParassetGovernance(governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov"); _governance = newGovernance; } /// @dev Uniform accuracy /// @param inputToken Initial token /// @param inputTokenAmount Amount of token /// @param outputToken Converted token /// @return stability Amount of outputToken function getDecimalConversion( address inputToken, uint256 inputTokenAmount, address outputToken ) public view returns(uint256) { uint256 inputTokenDec = 18; uint256 outputTokenDec = 18; if (inputToken != address(0x0)) { inputTokenDec = IERC20(inputToken).decimals(); } if (outputToken != address(0x0)) { outputTokenDec = IERC20(outputToken).decimals(); } return inputTokenAmount * (10**outputTokenDec) / (10**inputTokenDec); } //---------modifier------------ modifier onlyGovernance() { require(IParassetGovernance(_governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov"); _; } modifier nonReentrant() { require(_locked == 0, "Log:ParassetBase:!_locked"); _locked = 1; _; _locked = 0; } } // File: lib/TransferHelper.sol pragma solidity ^0.8.4; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: iface/IPriceController.sol pragma solidity ^0.8.4; interface IPriceController { /// @dev Get price /// @param token mortgage asset address /// @param uToken underlying asset address /// @param payback return address of excess fee /// @return tokenPrice Mortgage asset price(1 ETH = ? token) /// @return pTokenPrice PToken price(1 ETH = ? pToken) function getPriceForPToken( address token, address uToken, address payback ) external payable returns (uint256 tokenPrice, uint256 pTokenPrice); } // File: iface/IInsurancePool.sol pragma solidity ^0.8.4; interface IInsurancePool { /// @dev Destroy ptoken, update negative ledger /// @param amount quantity destroyed function destroyPToken(uint256 amount) external; /// @dev Clear negative books function eliminate() external; } // File: iface/IParasset.sol pragma solidity ^0.8.4; interface IParasset { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function destroy(uint256 amount, address account) external; function issuance(uint256 amount, address account) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: MortgagePool.sol pragma solidity ^0.8.4; contract MortgagePool is ParassetBase { Config _config; // mortgage asset address => mortgage config mapping(address=>MortgageInfo) _mortgageConfig; // mortgage asset address => ledger info mapping(address=>MortgageLeader) _ledgerList; // priceController contract IPriceController _query; // insurance pool contract IInsurancePool _insurancePool; // contract base num uint256 constant BASE_NUM = 100000; struct MortgageInfo { // allow mortgage bool mortgageAllow; // six digits, 0.75=75000 uint88 maxRate; // six digits, 1.3=130000 uint80 k; // six digits, 0.02=2000 uint40 r0; // liquidation rate 90000=90% uint40 liquidateRate; } struct MortgageLeader { // debt data PersonalLedger[] ledgerArray; // users who have created debt positions(address) mapping(address => uint256) accountMapping; } struct PersonalLedger { // amount of mortgaged assets uint256 mortgageAssets; // amount of debt(PToken,Stability fee not included) uint256 parassetAssets; // the block height of the last operation uint160 blockHeight; // mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) uint88 rate; } struct Config { // pToken address address pTokenAdd; // amount of blocks produced in a year uint96 oneYearBlock; // underlyingToken address address underlyingTokenAdd; // = 0: pause // = 1: active // = 2: out only uint96 flag; } event FeeValue(uint256 value); event LedgerLog(address mToken, uint256 mTokenAmount, uint256 pTokenAmount, uint256 tokenPrice, uint256 pTokenPrice, uint88 rate); //---------modifier--------- modifier whenActive() { require(_config.flag == 1, "Log:MortgagePool:!active"); _; } modifier outOnly() { require(_config.flag != 0, "Log:MortgagePool:!0"); _; } //---------view--------- /// @dev Calculate the stability fee /// @param parassetAssets Amount of debt(PToken,Stability fee not included) /// @param blockHeight The block height of the last operation /// @param rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @param nowRate Current mortgage rate (not including stability fee) /// @param r0Value Market base interest rate /// @return fee function getFee( uint256 parassetAssets, uint160 blockHeight, uint256 rate, uint256 nowRate, uint40 r0Value ) public view returns(uint256) { uint256 top = (uint256(2) * (rate + nowRate) + BASE_NUM) * parassetAssets * uint256(r0Value) * (block.number - uint256(blockHeight)); uint256 bottom = BASE_NUM * BASE_NUM * uint256(_config.oneYearBlock); return top / bottom; } /// @dev Calculate the mortgage rate /// @param mortgageAssets Amount of mortgaged assets /// @param parassetAssets Amount of debt /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @return mortgage rate function getMortgageRate( uint256 mortgageAssets, uint256 parassetAssets, uint256 tokenPrice, uint256 pTokenPrice ) public pure returns(uint256) { if (mortgageAssets == 0) { return 0; } return parassetAssets * tokenPrice * BASE_NUM / (pTokenPrice * mortgageAssets); } /// @dev Get real-time data of the current debt warehouse /// @param mortgageToken Mortgage asset address /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param uTokenPrice Underlying asset price(1 ETH = ? Underlying asset) /// @param maxRateNum Maximum mortgage rate /// @param owner Debt owner /// @return fee Stability fee /// @return mortgageRate Real-time mortgage rate(Including stability fee) /// @return maxSubM The maximum amount of mortgage assets can be reduced /// @return maxAddP Maximum number of coins that can be added function getInfoRealTime( address mortgageToken, uint256 tokenPrice, uint256 uTokenPrice, uint88 maxRateNum, address owner ) external view returns( uint256 fee, uint256 mortgageRate, uint256 maxSubM, uint256 maxAddP ) { address mToken = mortgageToken; MortgageLeader storage mLedger = _ledgerList[mToken]; if (mLedger.accountMapping[address(owner)] == 0) { return (0,0,0,0); } PersonalLedger memory pLedger = mLedger.ledgerArray[mLedger.accountMapping[address(owner)] - 1]; if (pLedger.mortgageAssets == 0 && pLedger.parassetAssets == 0) { return (0,0,0,0); } uint256 pTokenPrice = getDecimalConversion(_config.underlyingTokenAdd, uTokenPrice, _config.pTokenAdd); uint256 tokenPriceAmount = tokenPrice; fee = getFee(pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPriceAmount, pTokenPrice), _mortgageConfig[mToken].r0); mortgageRate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets + fee, tokenPriceAmount, pTokenPrice); uint256 mRateNum = maxRateNum; if (mortgageRate >= mRateNum) { maxSubM = 0; maxAddP = 0; } else { maxSubM = pLedger.mortgageAssets - (pLedger.parassetAssets * tokenPriceAmount * BASE_NUM / (mRateNum * pTokenPrice)); maxAddP = pLedger.mortgageAssets * pTokenPrice * mRateNum / (BASE_NUM * tokenPriceAmount) - pLedger.parassetAssets; } } /// @dev View debt warehouse data /// @param mortgageToken mortgage asset address /// @param owner debt owner /// @return mortgageAssets amount of mortgaged assets /// @return parassetAssets amount of debt(PToken,Stability fee not included) /// @return blockHeight the block height of the last operation /// @return rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @return created is it created function getLedger( address mortgageToken, address owner ) public view returns( uint256 mortgageAssets, uint256 parassetAssets, uint160 blockHeight, uint88 rate, bool created ) { MortgageLeader storage mLedger = _ledgerList[mortgageToken]; if (mLedger.accountMapping[address(owner)] == 0) { return (0,0,0,0,false); } PersonalLedger memory pLedger = mLedger.ledgerArray[mLedger.accountMapping[address(owner)] - 1]; return (pLedger.mortgageAssets, pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, true); } /// @dev View the insurance pool address /// @return insurance pool address function getInsurancePool() external view returns(address) { return address(_insurancePool); } /// @dev View the market base interest rate /// @return market base interest rate function getR0(address mortgageToken) external view returns(uint40) { return _mortgageConfig[mortgageToken].r0; } /// @dev View the liquidation rate /// @return liquidation rate function getLiquidateRate(address mortgageToken) external view returns(uint40) { return _mortgageConfig[mortgageToken].liquidateRate; } /// @dev View the amount of blocks produced in a year /// @return amount of blocks produced in a year function getOneYear() external view returns(uint96) { return _config.oneYearBlock; } /// @dev View the maximum mortgage rate /// @param mortgageToken Mortgage asset address /// @return maximum mortgage rate function getMaxRate(address mortgageToken) external view returns(uint88) { return _mortgageConfig[mortgageToken].maxRate; } /// @dev View the k value /// @param mortgageToken Mortgage asset address /// @return k value function getK(address mortgageToken) external view returns(uint256) { return _mortgageConfig[mortgageToken].k; } /// @dev View the priceController contract address /// @return priceController contract address function getPriceController() external view returns(address) { return address(_query); } /// @dev View the debt array length /// @param mortgageToken mortgage asset address /// @return debt array length function getLedgerArrayNum(address mortgageToken) external view returns(uint256) { return _ledgerList[mortgageToken].ledgerArray.length; } /// @dev View the debt index /// @param mortgageToken mortgage asset address /// @param owner debt owner /// @return index function getLedgerIndex( address mortgageToken, address owner ) external view returns(uint256) { MortgageLeader storage mLedger = _ledgerList[mortgageToken]; return mLedger.accountMapping[address(owner)]; } /// @dev View the pToken address /// @return pToken address function getPTokenAddress() external view returns(address) { return _config.pTokenAdd; } /// @dev View the underlyingToken address /// @return underlyingToken address function getUnderlyingToken() external view returns(address) { return _config.underlyingTokenAdd; } /// @dev View the flag num /// @return flag num function getFlag() external view returns(uint96) { return _config.flag; } //---------governance---------- /// @dev Set mortgage pool parameters /// @param pTokenAdd pToken address /// @param oneYear number of blocks in a year /// @param underlyingTokenAdd underlying asset address /// @param flag current state of the contract function setConfig( address pTokenAdd, uint96 oneYear, address underlyingTokenAdd, uint96 flag ) public onlyGovernance { _config.pTokenAdd = pTokenAdd; _config.oneYearBlock = oneYear; _config.underlyingTokenAdd = underlyingTokenAdd; _config.flag = flag; } /// @dev Set contract status /// @param num 0: pause, 1: active, 2: out only function setFlag(uint96 num) public onlyGovernance { _config.flag = num; } /// @dev Allow asset mortgage to generate PToken /// @param mortgageToken mortgage asset address /// @param allow allow mortgage function setMortgageAllow(address mortgageToken, bool allow) public onlyGovernance { _mortgageConfig[mortgageToken].mortgageAllow = allow; } /// @dev Set insurance pool contract /// @param add insurance pool contract function setInsurancePool(address add) public onlyGovernance { _insurancePool = IInsurancePool(add); } /// @dev Set liquidation rate /// @param num liquidation rate, 90000=90% function setLiquidateRate(address mortgageToken, uint40 num) public onlyGovernance { _mortgageConfig[mortgageToken].liquidateRate = num; } /// @dev Set market base interest rate /// @param num market base interest rate(num = ? * 1 ether) function setR0(address mortgageToken, uint40 num) public onlyGovernance { _mortgageConfig[mortgageToken].r0 = num; } /// @dev Set the amount of blocks produced in a year /// @param num amount of blocks produced in a year function setOneYear(uint96 num) public onlyGovernance { _config.oneYearBlock = num; } /// @dev Set K value /// @param mortgageToken mortgage asset address /// @param num K value function setK(address mortgageToken, uint80 num) public onlyGovernance { _mortgageConfig[mortgageToken].k = num; } /// @dev Set the maximum mortgage rate /// @param mortgageToken mortgage asset address /// @param num maximum mortgage rate(num = ? * 1000) function setMaxRate(address mortgageToken, uint88 num) public onlyGovernance { _mortgageConfig[mortgageToken].maxRate = num; } /// @dev Set priceController contract address /// @param add priceController contract address function setPriceController(address add) public onlyGovernance { _query = IPriceController(add); } /// @dev Set the underlying asset and PToken mapping and /// @param uToken underlying asset address /// @param pToken PToken address function setInfo(address uToken, address pToken) public onlyGovernance { _config.pTokenAdd = pToken; _config.underlyingTokenAdd = uToken; } //---------transaction--------- /// @dev Mortgage asset casting PToken /// @param mortgageToken mortgage asset address /// @param amount amount of mortgaged assets /// @param rate custom mortgage rate function coin( address mortgageToken, uint256 amount, uint88 rate ) public payable whenActive nonReentrant { MortgageInfo memory morInfo = _mortgageConfig[mortgageToken]; require(morInfo.mortgageAllow, "Log:MortgagePool:!mortgageAllow"); require(rate > 0 && rate <= morInfo.maxRate, "Log:MortgagePool:rate!=0"); require(amount > 0, "Log:MortgagePool:amount!=0"); MortgageLeader storage mLedger = _ledgerList[mortgageToken]; uint256 ledgerNum = mLedger.accountMapping[msg.sender]; if (ledgerNum == 0) { // create mLedger.ledgerArray.push(); mLedger.accountMapping[msg.sender] = mLedger.ledgerArray.length; } PersonalLedger storage pLedger = mLedger.ledgerArray[mLedger.accountMapping[msg.sender] - 1]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { TransferHelper.safeTransferFrom(mortgageToken, msg.sender, address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, uint256(msg.value) - amount); } // Calculate the stability fee transferFee(pLedger, tokenPrice, pTokenPrice, morInfo.r0); // Additional PToken issuance uint256 pTokenAmount = amount * pTokenPrice * rate / (tokenPrice * BASE_NUM); IParasset(_config.pTokenAdd).issuance(pTokenAmount, msg.sender); // Update debt information pLedger.mortgageAssets = mortgageAssets + amount; pLedger.parassetAssets = parassetAssets + pTokenAmount; pLedger.blockHeight = uint160(block.number); pLedger.rate = uint88(getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice)); emit LedgerLog(mortgageToken, pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice, pLedger.rate); } /// @dev Increase mortgage assets /// @param mortgageToken mortgage asset address /// @param amount amount of mortgaged assets function supplement(address mortgageToken, uint256 amount) public payable outOnly nonReentrant { MortgageInfo memory morInfo = _mortgageConfig[mortgageToken]; require(morInfo.mortgageAllow, "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); MortgageLeader storage mLedger = _ledgerList[mortgageToken]; uint256 ledgerNum = mLedger.accountMapping[msg.sender]; if (ledgerNum == 0) { // create mLedger.ledgerArray.push(); mLedger.accountMapping[msg.sender] = mLedger.ledgerArray.length; } PersonalLedger storage pLedger = mLedger.ledgerArray[mLedger.accountMapping[msg.sender] - 1]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { TransferHelper.safeTransferFrom(mortgageToken, msg.sender, address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, uint256(msg.value) - amount); } // Calculate the stability fee transferFee(pLedger, tokenPrice, pTokenPrice, morInfo.r0); // Update debt information pLedger.mortgageAssets = mortgageAssets + amount; pLedger.blockHeight = uint160(block.number); pLedger.rate = uint88(getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); emit LedgerLog(mortgageToken, pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice, pLedger.rate); } /// @dev Reduce mortgage assets /// @param mortgageToken mortgage asset address /// @param amount amount of mortgaged assets function decrease(address mortgageToken, uint256 amount) public payable outOnly nonReentrant { MortgageInfo memory morInfo = _mortgageConfig[mortgageToken]; require(morInfo.mortgageAllow, "Log:MortgagePool:!mortgageAllow"); MortgageLeader storage mLedger = _ledgerList[mortgageToken]; uint256 ledgerNum = mLedger.accountMapping[msg.sender]; require(ledgerNum != 0, "Log:MortgagePool:index=0"); PersonalLedger storage pLedger = mLedger.ledgerArray[ledgerNum - 1]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, msg.value); // Calculate the stability fee transferFee(pLedger, tokenPrice, pTokenPrice, morInfo.r0); // Update debt information pLedger.mortgageAssets = mortgageAssets - amount; pLedger.blockHeight = uint160(block.number); if (pLedger.mortgageAssets == 0) { require(pLedger.parassetAssets == 0, "Log:MortgagePool:!parassetAssets"); pLedger.rate == 0; } else { uint256 newRate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(newRate <= uint256(morInfo.maxRate), "Log:MortgagePool:!maxRate"); pLedger.rate = uint88(newRate); } emit LedgerLog(mortgageToken, pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice, pLedger.rate); // Transfer out mortgage assets if (mortgageToken != address(0x0)) { TransferHelper.safeTransfer(mortgageToken, msg.sender, amount); } else { TransferHelper.safeTransferETH(msg.sender, amount); } } /// @dev Increase debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param amount amount of debt function increaseCoinage(address mortgageToken, uint256 amount) public payable whenActive nonReentrant { MortgageInfo memory morInfo = _mortgageConfig[mortgageToken]; require(morInfo.mortgageAllow, "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); MortgageLeader storage mLedger = _ledgerList[mortgageToken]; uint256 ledgerNum = mLedger.accountMapping[msg.sender]; require(ledgerNum != 0, "Log:MortgagePool:index=0"); PersonalLedger storage pLedger = mLedger.ledgerArray[ledgerNum - 1]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(mortgageAssets > 0, "Log:MortgagePool:!mortgageAssets"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, msg.value); // Calculate the stability fee transferFee(pLedger, tokenPrice, pTokenPrice, morInfo.r0); // Update debt information pLedger.parassetAssets = parassetAssets + amount; pLedger.blockHeight = uint160(block.number); uint256 newRate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(newRate <= uint256(morInfo.maxRate), "Log:MortgagePool:!maxRate"); pLedger.rate = uint88(newRate); emit LedgerLog(mortgageToken, pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice, pLedger.rate); // Additional PToken issuance IParasset(_config.pTokenAdd).issuance(amount, msg.sender); } /// @dev Reduce debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param amount amount of debt function reducedCoinage(address mortgageToken, uint256 amount) public payable outOnly nonReentrant { MortgageInfo memory morInfo = _mortgageConfig[mortgageToken]; require(morInfo.mortgageAllow, "Log:MortgagePool:!mortgageAllow"); MortgageLeader storage mLedger = _ledgerList[mortgageToken]; uint256 ledgerNum = mLedger.accountMapping[msg.sender]; require(ledgerNum != 0, "Log:MortgagePool:index=0"); PersonalLedger storage pLedger = mLedger.ledgerArray[ledgerNum - 1]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= parassetAssets, "Log:MortgagePool:!amount"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, msg.value); // Calculate the stability fee transferFee(pLedger, tokenPrice, pTokenPrice, morInfo.r0); // Update debt information pLedger.parassetAssets = parassetAssets - amount; pLedger.blockHeight = uint160(block.number); pLedger.rate = uint88(getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice)); emit LedgerLog(mortgageToken, pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice, pLedger.rate); TransferHelper.safeTransferFrom(_config.pTokenAdd, msg.sender, address(this), amount); // Destroy PToken IParasset(_config.pTokenAdd).destroy(amount, address(this)); } /// @dev Liquidation of debt /// @param mortgageToken mortgage asset address /// @param account debt owner address /// @param amount amount of mortgaged assets /// @param pTokenAmountLimit pay PToken limit function liquidation( address mortgageToken, address account, uint256 amount, uint256 pTokenAmountLimit ) public payable outOnly nonReentrant { MortgageInfo memory morInfo = _mortgageConfig[mortgageToken]; require(morInfo.mortgageAllow, "Log:MortgagePool:!mortgageAllow"); MortgageLeader storage mLedger = _ledgerList[mortgageToken]; uint256 ledgerNum = mLedger.accountMapping[address(account)]; require(ledgerNum != 0, "Log:MortgagePool:index=0"); PersonalLedger storage pLedger = mLedger.ledgerArray[ledgerNum - 1]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, msg.value); // Judging the liquidation line _checkLine(pLedger, tokenPrice, pTokenPrice, morInfo.k, morInfo.r0); // Calculate the amount of PToken uint256 pTokenAmount = amount * pTokenPrice * uint256(morInfo.liquidateRate) / (tokenPrice * BASE_NUM); // Transfer to PToken require(pTokenAmount <= pTokenAmountLimit, "Log:MortgagePool:!pTokenAmountLimit"); TransferHelper.safeTransferFrom(_config.pTokenAdd, msg.sender, address(_insurancePool), pTokenAmount); // Calculate the debt for destruction uint256 offset = parassetAssets * amount / mortgageAssets; // Destroy PToken _insurancePool.destroyPToken(offset); // Update debt information pLedger.mortgageAssets = mortgageAssets - amount; pLedger.parassetAssets = parassetAssets - offset; emit LedgerLog(mortgageToken, pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice, pLedger.rate); // MortgageAssets liquidation, mortgage rate and block number are not updated if (pLedger.mortgageAssets == 0) { pLedger.parassetAssets = 0; pLedger.blockHeight = 0; pLedger.rate = 0; } // Transfer out mortgage asset if (mortgageToken != address(0x0)) { TransferHelper.safeTransfer(mortgageToken, msg.sender, amount); } else { TransferHelper.safeTransferETH(msg.sender, amount); } } /// @dev Check the liquidation line /// @param pLedger debt warehouse ledger /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) function _checkLine( PersonalLedger memory pLedger, uint256 tokenPrice, uint256 pTokenPrice, uint80 kValue, uint40 r0Value ) public view { uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // The current mortgage rate cannot exceed the liquidation line uint256 mortgageRate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); uint256 fee = 0; uint160 blockHeight = pLedger.blockHeight; if (parassetAssets > 0 && block.number > uint256(blockHeight) && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, mortgageRate, r0Value); } require(((parassetAssets + fee) * uint256(kValue) * tokenPrice / (mortgageAssets * BASE_NUM)) > pTokenPrice, "Log:MortgagePool:!liquidationLine"); } function transferFee( PersonalLedger memory pLedger, uint256 tokenPrice, uint256 pTokenPrice, uint40 r0Value ) private { uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; uint256 rate = pLedger.rate; uint160 blockHeight = pLedger.blockHeight; if (parassetAssets > 0 && block.number > uint256(blockHeight) && blockHeight != 0) { uint256 fee = getFee(parassetAssets, blockHeight, rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice), r0Value); // The stability fee is transferred to the insurance pool TransferHelper.safeTransferFrom(_config.pTokenAdd, msg.sender, address(_insurancePool), fee); // Eliminate negative accounts _insurancePool.eliminate(); emit FeeValue(fee); } } /// @dev Get price /// @param mortgageToken mortgage asset address /// @param priceValue price fee /// @return tokenPrice Mortgage asset price(1 ETH = ? token) /// @return pTokenPrice PToken price(1 ETH = ? pToken) function getPriceForPToken( address mortgageToken, uint256 priceValue ) private returns ( uint256 tokenPrice, uint256 pTokenPrice ) { (tokenPrice, pTokenPrice) = _query.getPriceForPToken{value:priceValue}(mortgageToken, _config.underlyingTokenAdd, msg.sender); } }
Set K value mortgageToken mortgage asset address num K value
function setK(address mortgageToken, uint80 num) public onlyGovernance { _mortgageConfig[mortgageToken].k = num; }
10,785,913
./partial_match/3/0x965c2E8948E8d0387855fA80A8e75697b29118a6/sources/Qstroller.sol
Transfers collateral tokens (this market) to the liquidator. Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. seizerToken The contract seizing the collateral (i.e. borrowed cToken) liquidator The account receiving seized collateral borrower The account having collateral seized seizeTokens The number of cTokens to seize return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Admin Functions / Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. newPendingAdmin New pending admin. return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller = admin
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint); function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } return uint(Error.NO_ERROR); }
5,085,048
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => bool) isAddressAuthorized; address[] private airlines; mapping(address => bool) isAirline; // mapping makes the isAirline modifier simple to understand mapping(address => bool) isAirlineFeePaid; address[] private passengers; mapping(address => bool) isPassenger; mapping(address => uint256) passengerBalance; bytes32[] private flightKeys; //airline, flightName, timestamp mapping(bytes32 => Flight) private flights; struct Insurance { address passenger; uint256 amountInsured; uint256 amountPayout; } struct Flight { bool isRegistered; uint8 statusCode; address airline; string flightName; uint256 updatedTimestamp; } mapping(bytes32 => Insurance[]) insurances; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event dataContractFunded(); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() payable { contractOwner = msg.sender; isAddressAuthorized[contractOwner] = true; isAddressAuthorized[address(this)] = true; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireCallerIsAuthorized() { require(isAddressAuthorized[msg.sender], "Caller is not authorized"); _; } /** * @dev Modifier that requires only registered airlines can call this function */ modifier requireIsAirline(address inputAddress) { require(isAirline[inputAddress], "The supplied address is not an airline, cannot use this function"); _; } modifier requireIsAirlineFeePaid(address inputAddress) { require(isAirlineFeePaid[inputAddress], "The supplied address is not a funded airline, cannot use this function"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } function addAuthorizedCaller (address inputAddress) external requireContractOwner returns (bool) { isAddressAuthorized[inputAddress] = true; return isAddressAuthorized[inputAddress]; } function removeAuthorizedCaller (address inputAddress) external requireContractOwner { isAddressAuthorized[inputAddress] = false; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } function isAddressAirline(address inputAddress) external view requireIsOperational returns(bool) { return isAirline[inputAddress]; } function getAirline(uint index) external view requireIsOperational returns(address) { return airlines[index]; } function isCallerAuthorized(address inputAddress) external view requireIsOperational returns(bool) { return isAddressAuthorized[inputAddress]; } function isAddressFundedAirline(address inputAddress) external view requireIsOperational requireIsAirline(inputAddress) returns(bool) { return isAirlineFeePaid[inputAddress]; } function isAddressPassenger(address inputAddress) external view requireIsOperational returns(bool) { return isPassenger[inputAddress]; } function getInsurancePayoutAmount(address passenger) external view requireIsOperational // requireCallerIsAuthorized returns(uint256) { return passengerBalance[passenger]; } function getNumAirlines() external view requireIsOperational // requireCallerIsAuthorized returns(uint) { return airlines.length; } function getContractOwner() external view returns(address) { return contractOwner; } function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function getFlightKeysForUI() public view returns(bytes32[] memory) { return flightKeys; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airlineAddress) requireIsOperational // requireCallerIsAuthorized external { airlines.push(airlineAddress); isAirline[airlineAddress] = true; isAirlineFeePaid[airlineAddress] = false; isAddressAuthorized[airlineAddress] = true; } function registerFirstAirline(address initialAirline) requireIsOperational external { require(airlines.length <= 0, "This function can only be used once"); airlines.push(initialAirline); isAirline[initialAirline] = true; isAirlineFeePaid[initialAirline] = false; isAddressAuthorized[initialAirline] = true; // emit airline registration in dataContract only for initial airline // emit airlineRegistered(initialAirline); } function payAirlineFee(address airlineAddress) requireIsOperational // requireCallerIsAuthorized external { isAirlineFeePaid[airlineAddress] = true; } function registerPassenger(address passengerAddress) requireIsOperational // requireCallerIsAuthorized external { passengers.push(passengerAddress); isPassenger[passengerAddress] = true; passengerBalance[passengerAddress] = 0; } function registerFlight(address airline, string memory flightName, uint256 timestamp) requireIsOperational // requireCallerIsAuthorized external returns (bytes32) { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); flightKeys.push(flightKey); flights[flightKey] = Flight(true, 0, airline, flightName, timestamp); return flightKey; } function getFlightInfo(bytes32 flightKey) requireIsOperational // requireCallerIsAuthorized external view returns (address, string memory, uint256) { address airlineAddress = flights[flightKey].airline; string memory name = flights[flightKey].flightName; uint256 timeStamp = flights[flightKey].updatedTimestamp; return (airlineAddress, name, timeStamp); } /** * @dev Buy insurance for a flight * */ function buy(address passenger, string memory flightName, uint256 value, address airline, uint256 timeStamp) requireIsOperational // requireCallerIsAuthorized external { bytes32 flightKey = getFlightKey(airline, flightName, timeStamp); Insurance memory newInsurance; newInsurance.passenger = passenger; newInsurance.amountInsured = value; uint256 insuranceBonus = value / 2; newInsurance.amountPayout = value + insuranceBonus; insurances[flightKey].push(newInsurance); } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, string memory flight, uint256 timestamp) requireIsOperational // requireCallerIsAuthorized external { bytes32 flightKey = getFlightKey(airline, flight, timestamp); for (uint8 i = 0; i < insurances[flightKey].length; i++) { address passengerToCredit = insurances[flightKey][i].passenger; uint256 amountToCredit = insurances[flightKey][i].amountPayout; passengerBalance[passengerToCredit] = amountToCredit; insurances[flightKey][i].amountPayout = 0; } } function claimInsurance(address passenger) requireIsOperational // requireCallerIsAuthorized payable external { require(passengerBalance[passenger] > 0, "There is nothing to claim"); uint256 payout = passengerBalance[passenger]; passengerBalance[passenger] = 0; address payable payablePassenger = payable(address(passenger)); safeTransfer(payablePassenger, payout); } //https://solidity-by-example.org/sending-ether/ function safeTransfer(address payable _to, uint256 _amount) requireIsOperational payable public { //https://solidity-by-example.org/sending-ether/ (bool sent, bytes memory data) = _to.call{value: _amount}(""); require(sent, "Failed to send Ether"); } function fund() payable external { safeTransfer(payable(address(this)), msg.value); } fallback() external payable { // emit dataContractFunded(); } receive() external payable { // emit dataContractFunded(); } }
requireCallerIsAuthorized
function getFlightInfo(bytes32 flightKey) requireIsOperational external view returns (address, string memory, uint256) { address airlineAddress = flights[flightKey].airline; string memory name = flights[flightKey].flightName; uint256 timeStamp = flights[flightKey].updatedTimestamp; return (airlineAddress, name, timeStamp); }
14,023,987
./full_match/42220/0x15bBc9BB2b7C46DD618fC487d959c7395F2E7b0D/sources/contracts/WeightedPool2Tokens.sol
1e18 corresponds to 1.0, or a 100% fee The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE. The protocol fees will always be charged using the token associated with the max weight in the pool. Since these Pools will register tokens only once, we can assume this index will be constant. All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported.
{ using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; using WeightedPool2TokensMiscData for bytes32; uint256 private constant _MINIMUM_BPT = 1e6; bytes32 internal _miscData; uint256 private _lastInvariant; IVault private immutable _vault; bytes32 private immutable _poolId; IERC20 internal immutable _token0; IERC20 internal immutable _token1; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; uint256 private immutable _maxWeightTokenIndex; uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; event OracleEnabledChanged(bool enabled); event SwapFeePercentageChanged(uint256 swapFeePercentage); modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } struct NewPoolParams { IVault vault; string name; string symbol; IERC20 token0; IERC20 token1; uint256 normalizedWeight0; uint256 normalizedWeight1; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; bool oracleEnabled; address owner; } constructor(NewPoolParams memory params) BalancerPoolToken(params.name, params.symbol) BasePoolAuthorization(params.owner) TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration) Authentication(bytes32(uint256(msg.sender))) { _setOracleEnabled(params.oracleEnabled); _setSwapFeePercentage(params.swapFeePercentage); bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN); IERC20[] memory tokens = new IERC20[](2); tokens[0] = params.token0; tokens[1] = params.token1; params.vault.registerTokens(poolId, tokens, new address[](2)); _vault = params.vault; _poolId = poolId; _token0 = params.token0; _token1 = params.token1; _scalingFactor0 = _computeScalingFactor(params.token0); _scalingFactor1 = _computeScalingFactor(params.token1); _require(params.normalizedWeight0 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); _require(params.normalizedWeight1 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1); _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _normalizedWeight0 = params.normalizedWeight0; _normalizedWeight1 = params.normalizedWeight1; _maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1; } function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function getMiscData() external view returns ( int256 logInvariant, int256 logTotalSupply, uint256 oracleSampleCreationTimestamp, uint256 oracleIndex, bool oracleEnabled, uint256 swapFeePercentage ) { bytes32 miscData = _miscData; logInvariant = miscData.logInvariant(); logTotalSupply = miscData.logTotalSupply(); oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp(); oracleIndex = miscData.oracleIndex(); oracleEnabled = miscData.oracleEnabled(); swapFeePercentage = miscData.swapFeePercentage(); } function getSwapFeePercentage() public view returns (uint256) { return _miscData.swapFeePercentage(); } function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.setSwapFeePercentage(swapFeePercentage); emit SwapFeePercentageChanged(swapFeePercentage); } function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function _setOracleEnabled(bool enabled) internal { _miscData = _miscData.setOracleEnabled(enabled); emit OracleEnabledChanged(enabled); } function setPaused(bool paused) external authenticate { _setPaused(paused); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256[] memory normalizedWeights = new uint256[](2); normalizedWeights[0] = _normalizedWeights(true); normalizedWeights[1] = _normalizedWeights(false); return normalizedWeights; } function _normalizedWeights(bool token0) internal view virtual returns (uint256) { return token0 ? _normalizedWeight0 : _normalizedWeight1; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); _upscaleArray(balances); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); _updateOracle( request.lastChangeBlock, tokenInIsToken0 ? balanceTokenIn : balanceTokenOut, tokenInIsToken0 ? balanceTokenOut : balanceTokenIn ); if (request.kind == IVault.SwapKind.GIVEN_IN) { uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); return _downscaleDown(amountOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); return amountIn.divUp(getSwapFeePercentage().complement()); } } function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); _updateOracle( request.lastChangeBlock, tokenInIsToken0 ? balanceTokenIn : balanceTokenOut, tokenInIsToken0 ? balanceTokenOut : balanceTokenIn ); if (request.kind == IVault.SwapKind.GIVEN_IN) { uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); return _downscaleDown(amountOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); return amountIn.divUp(getSwapFeePercentage().complement()); } } } else { function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { return WeightedMath._calcInGivenOut( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) whenNotPaused returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { uint256 bptAmountOut; if (totalSupply() == 0) { (bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData); _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); _downscaleUpArray(amountsIn); dueProtocolFeeAmounts = new uint256[](2); _upscaleArray(balances); _updateOracle(lastChangeBlock, balances[0], balances[1]); (bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _mintPoolTokens(recipient, bptAmountOut); _downscaleUpArray(amountsIn); _downscaleDownArray(dueProtocolFeeAmounts); } } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) whenNotPaused returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { uint256 bptAmountOut; if (totalSupply() == 0) { (bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData); _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); _downscaleUpArray(amountsIn); dueProtocolFeeAmounts = new uint256[](2); _upscaleArray(balances); _updateOracle(lastChangeBlock, balances[0], balances[1]); (bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _mintPoolTokens(recipient, bptAmountOut); _downscaleUpArray(amountsIn); _downscaleDownArray(dueProtocolFeeAmounts); } } } else { _cacheInvariantAndSupply(); function _onInitializePool( bytes32, address, address, bytes memory userData ) private returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256, uint256[] memory, uint256[] memory ) { uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); _mutateAmounts(balances, amountsIn, FixedPoint.add); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); if (kind == WeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); _revert(Errors.UNHANDLED_JOIN_KIND); } } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); if (kind == WeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); _revert(Errors.UNHANDLED_JOIN_KIND); } } } else if (kind == WeightedPool.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { } else { function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), getSwapFeePercentage() ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](2); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), getSwapFeePercentage() ); return (bptAmountOut, amountsIn); } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { _upscaleArray(balances); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _burnPoolTokens(sender, bptAmountIn); _downscaleDownArray(amountsOut); _downscaleDownArray(dueProtocolFeeAmounts); if (_isNotPaused()) { _cacheInvariantAndSupply(); } return (amountsOut, dueProtocolFeeAmounts); } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { _upscaleArray(balances); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _burnPoolTokens(sender, bptAmountIn); _downscaleDownArray(amountsOut); _downscaleDownArray(dueProtocolFeeAmounts); if (_isNotPaused()) { _cacheInvariantAndSupply(); } return (amountsOut, dueProtocolFeeAmounts); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { _updateOracle(lastChangeBlock, balances[0], balances[1]); uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); dueProtocolFeeAmounts = new uint256[](2); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { _updateOracle(lastChangeBlock, balances[0], balances[1]); uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); dueProtocolFeeAmounts = new uint256[](2); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } } else { _mutateAmounts(balances, amountsOut, FixedPoint.sub); function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.ExitKind kind = userData.exitKind(); if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); return _exitExactBPTInForTokensOut(balances, userData); return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.ExitKind kind = userData.exitKind(); if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); return _exitExactBPTInForTokensOut(balances, userData); return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } } else if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { } else { function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsOut = new uint256[](2); amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { uint256 bptAmountIn = userData.exactBptInForTokensOut(); uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, 2); _upscaleArray(amountsOut); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } function getLargestSafeQueryWindow() external pure override returns (uint256) { return 34 hours; } function getLatest(Variable variable) external view override returns (uint256) { int256 instantValue = _getInstantValue(variable, _miscData.oracleIndex()); return _fromLowResLog(instantValue); } function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view override returns (uint256[] memory results) { results = new uint256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAverageQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; _require(query.secs != 0, Errors.ORACLE_BAD_SECS); int256 beginAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago + query.secs); int256 endAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago); results[i] = _fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs)); } } function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view override returns (uint256[] memory results) { results = new uint256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAverageQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; _require(query.secs != 0, Errors.ORACLE_BAD_SECS); int256 beginAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago + query.secs); int256 endAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago); results[i] = _fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs)); } } function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view override returns (int256[] memory results) { results = new int256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAccumulatorQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; results[i] = _getPastAccumulator(query.variable, oracleIndex, query.ago); } } function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view override returns (int256[] memory results) { results = new int256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAccumulatorQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; results[i] = _getPastAccumulator(query.variable, oracleIndex, query.ago); } } function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } function _cacheInvariantAndSupply() internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(WeightedOracleMath._toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(WeightedOracleMath._toLowResLog(totalSupply())); _miscData = miscData; } } function _cacheInvariantAndSupply() internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(WeightedOracleMath._toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(WeightedOracleMath._toLowResLog(totalSupply())); _miscData = miscData; } } function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); return (bptOut, amountsIn); } function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); return (bptIn, amountsOut); } function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { uint256[] memory dueProtocolFeeAmounts = new uint256[](2); if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { uint256[] memory dueProtocolFeeAmounts = new uint256[](2); if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private pure { toMutate[0] = mutation(toMutate[0], arguments[0]); toMutate[1] = mutation(toMutate[1], arguments[1]); } function getRate() public view returns (uint256) { return Math.mul(getInvariant(), 2).divDown(totalSupply()); } function _computeScalingFactor(IERC20 token) private view returns (uint256) { uint256 tokenDecimals = ERC20(address(token)).decimals(); uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; } function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); } function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } function _downscaleDownArray(uint256[] memory amounts) internal view { amounts[0] = Math.divDown(amounts[0], _scalingFactor(true)); amounts[1] = Math.divDown(amounts[1], _scalingFactor(false)); } function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } function _downscaleUpArray(uint256[] memory amounts) internal view { amounts[0] = Math.divUp(amounts[0], _scalingFactor(true)); amounts[1] = Math.divUp(amounts[1], _scalingFactor(false)); } function _getAuthorizer() internal view override returns (IAuthorizer) { return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } returndatacopy(0, 0x04, 32) mstore(0x20, 64) returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) return(0, add(returndatasize(), 28)) function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } } else { function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { if (msg.sender != address(this)) { (bool success, ) = address(this).call(msg.data); assembly { switch success case 0 { returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } default { invalid() } } _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); assembly { let size := mul(mload(tokenAmounts), 32) let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) revert(start, add(size, 68)) } } } }
16,342,104
/** *Submitted for verification at Etherscan.io on 2022-02-16 */ // SPDX-License-Identifier: GNU GPLv3 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; } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity 0.8.4; abstract contract ERC20Clone { function initializer( address _minter, string memory _wrappedTokenName, string memory _wrappedTokenTicker, uint8 _wrappedTokenDecimals, uint256 _vestEndTime ) public virtual; } pragma solidity 0.8.4; /// @title ERC20Factory contract for mass deployment of WVTs /// @author Capx Team /// @notice Only the controller contract can call the function which deploys cheap copy of ERC20 contracts /// @dev This contract uses EIP-1167: Minimal Proxy Contract contract ERC20Factory is Ownable { address public implementation; address public controller; address public lender; constructor(address _implementaiton, address _controller) { require( _implementaiton != address(0) && _controller != address(0), "Invalid input" ); implementation = _implementaiton; controller = _controller; } /// @notice Function which can only be called by owner and used to set lender contract address. /// @param _lender The address of the lender contract. function setLender(address _lender) external onlyOwner { require(_lender != address(0), "Invalid input"); lender = _lender; } /// @notice Function called by controller contract to deploy new ERC20 token function createStorage( string memory _wrappedTokenName, string memory _wrappedTokenTicker, uint8 _wrappedTokenDecimals, uint256 _vestEndTime ) public returns (address) { require(msg.sender == controller, "Only controller can access"); address clone = createClone(implementation); // Handling low level exception assert(clone != address(0)); ERC20Clone(clone).initializer( controller, _wrappedTokenName, _wrappedTokenTicker, _wrappedTokenDecimals, _vestEndTime ); return (clone); } /// @notice Function uses EIP-1167 implementation function createClone(address _target) internal returns (address result) { bytes20 targetBytes = bytes20(_target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } }
Function which can only be called by owner and used to set lender contract address. _lender The address of the lender contract.
function setLender(address _lender) external onlyOwner { require(_lender != address(0), "Invalid input"); lender = _lender; }
15,377,029
/// SPDX-License-Identifier: UNLICENSED /** ................ ..',,;;::::::::ccccc:;,'.. ..',;;;;::::::::::::cccccllllc;.. .';;;;;;;,'..............',:clllolc,. .,;;;;;,.. .';cooool;. .';;;;;'. ..... .,coodoc. .,;;;;'. ..',;:::cccc:;,'. .;odddl' .,;;;;. .,:cccclllllllllool:' ,odddl' .,:;:;. .;ccccc:;,''''',;cooooo:. ,odddc. ';:::' .,ccclc,.. .':odddc. .cdddo, .;:::,. ,cccc;. .:oddd:. ,dddd:. '::::' .ccll:. .ldddo' 'odddc. ,::c:. ,lllc' .';;;::::::::codddd; ,dxxxc. .,ccc:. .;lllc. ,oooooddddddddddddd; :dxxd: ,cccc. ;llll' .;:ccccccccccccccc;. 'oxxxo' 'cccc, 'loooc. 'lxxxd; .:lll:. .;ooooc. .;oxxxd:. ,llll;. .;ooddo:'. ..:oxxxxo;. .:llol,. 'coddddl:;''.........,;codxxxxd:. .:lool;. .':odddddddddoooodddxxxxxxdl;. .:ooooc' .';codddddddxxxxxxdol:,. .;ldddoc'. ...'',,;;;,,''.. .:oddddl:'. .,;:'. .:odddddoc;,... ..',:ldxxxx; .,:odddddddoolcc::::::::cllodxxxxxxxd:. .';clddxxxxxxxxxxxxxxxxxxxxxxoc;'. ..',;:ccllooooooollc:;,'.. ...... **/ pragma solidity 0.8.11; import "../general/RcaGovernable.sol"; import "../library/MerkleProof.sol"; import "../interfaces/IRcaShield.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title RCA Controller * @notice Controller contract for all RCA vaults. * This contract creates vaults, emits events when anything happens on a vault, * keeps track of variables relevant to vault functionality, keeps track of capacities, * amounts for sale on each vault, prices of tokens, and updates vaults when needed. * @author Robert M.C. Forster, Romke Jonker, Taek Lee, Chiranjibi Poudyal */ contract RcaController is RcaGovernable { /// @notice Address => whether or not it's a verified shield. mapping(address => bool) public shieldMapping; /// @notice Address => whether or not shield is active. mapping(address => bool) public activeShields; /// @notice Address => whether or not router is verified. mapping(address => bool) public isRouterVerified; /// @notice Fees for users per year for using the system. Ideally just 0 but option is here. /// In hundredths of %. 1000 == 10%. uint256 public apr; /// @notice Amount of time users must wait to withdraw tokens after requesting redemption. In seconds. uint256 public withdrawalDelay; /// @notice Discount for purchasing tokens being liquidated from a shield. 1000 == 10%. uint256 public discount; /// @notice Address that funds from selling tokens is sent to. address payable public treasury; /// @notice Amount of funds for sale on a protocol, sent in by DAO after a hack occurs (in token). bytes32 public liqForClaimsRoot; /// @notice The amount of each shield that's currently reserved for hack payouts. 1000 == 10%. bytes32 public reservedRoot; /// @notice Root of all underlying token prices--only used if the protocol is doing pricing. Price in Ether. bytes32 public priceRoot; /// @notice Nonce to prevent replays of capacity signatures. User => RCA nonce. mapping(address => uint256) public nonces; /// @notice Last time each individual shield was checked for update. mapping(address => uint256) public lastShieldUpdate; /** * @dev The update variable flow works in an interesting way to optimize efficiency: * Each time a user interacts with a specific shield vault, it calls Controller * for all necessary interactions (events & updates). The general Controller function * will check when when the last shield update was made vs. all recent other updates. * If a system update is more recent than the shield update, value is changed. */ struct SystemUpdates { uint32 liqUpdate; uint32 reservedUpdate; uint32 withdrawalDelayUpdate; uint32 discountUpdate; uint32 aprUpdate; uint32 treasuryUpdate; } SystemUpdates public systemUpdates; /** * @dev Events are used to notify the frontend of events on shields. If we have 1,000 shields, * a centralized event system can tell the frontend which shields to check for a specific user. */ event Mint(address indexed rcaShield, address indexed user, uint256 timestamp); event RedeemRequest(address indexed rcaShield, address indexed user, uint256 timestamp); event RedeemFinalize(address indexed rcaShield, address indexed user, uint256 timestamp); event Purchase(address indexed rcaShield, address indexed user, uint256 timestamp); event ShieldCreated( address indexed rcaShield, address indexed underlyingToken, string name, string symbol, uint256 timestamp ); event ShieldCancelled(address indexed rcaShield); ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// modifiers ////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Ensure the sender is a shield. * @dev We don't want non-shield contracts creating mint, redeem, purchase events. */ modifier onlyShield() { require(shieldMapping[msg.sender], "Caller must be a Shield Vault."); _; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////// constructor ///////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Construct with initial privileged addresses for controller. * @param _governor Complete control of the contracts. Can change all other owners. * @param _guardian Guardian multisig that can freeze percents after a hack. * @param _priceOracle Oracle that can submit price root to the ecosystem. * @param _capOracle Oracle that can submit capacity root to the ecosystem. * @param _apr Initial fees for the shield (1000 == 10%). * @param _discount Discount for purchasers of the token (1000 == 10%). * @param _withdrawalDelay Amount of time (in seconds) users must wait before withdrawing. * @param _treasury Address of the treasury that Ether funds will be sent to. */ constructor( address _governor, address _guardian, address _priceOracle, address _capOracle, uint256 _apr, uint256 _discount, uint256 _withdrawalDelay, address payable _treasury ) { initRcaGovernable(_governor, _guardian, _capOracle, _priceOracle); apr = _apr; discount = _discount; treasury = _treasury; withdrawalDelay = _withdrawalDelay; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// onlyShield ///////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Updates contract, emits event for minting, checks capacity. * @param _user User that is minting tokens. * @param _uAmount Underlying token amount being liquidated. * @param _expiry Time (Unix timestamp) that this request expires. * @param _v The recovery byte of the signature. * @param _r Half of the ECDSA signature pair. * @param _s Half of the ECDSA signature pair. * @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed. * @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed. */ function mint( address _user, uint256 _uAmount, uint256 _expiry, uint8 _v, bytes32 _r, bytes32 _s, uint256 _newCumLiqForClaims, bytes32[] calldata _liqForClaimsProof ) external onlyShield { _update(_newCumLiqForClaims, _liqForClaimsProof, 0, new bytes32[](0), false); // Confirm the capacity oracle approved this transaction. verifyCapacitySig(_user, _uAmount, _expiry, _v, _r, _s); emit Mint(msg.sender, _user, block.timestamp); } /** * @notice Updates contract, emits event for redeem action. * @param _user User that is redeeming tokens. * @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed. * @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed. * @param _newPercentReserved New percent of the shield that is reserved for hack payouts. * @param _percentReservedProof Merkle proof to verify the new percent reserved. */ function redeemRequest( address _user, uint256 _newCumLiqForClaims, bytes32[] calldata _liqForClaimsProof, uint256 _newPercentReserved, bytes32[] calldata _percentReservedProof ) external onlyShield { _update(_newCumLiqForClaims, _liqForClaimsProof, _newPercentReserved, _percentReservedProof, true); emit RedeemRequest(msg.sender, _user, block.timestamp); } /** * @notice Updates contract, emits event for redeem action, returns if router is verified. * @param _user User that is redeeming tokens. * @param _to Router address which should be used for zapping. * @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed. * @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed. * @param _newPercentReserved New percent of the shield that is reserved for hack payouts. * @param _percentReservedProof Merkle proof to verify the new percent reserved. */ function redeemFinalize( address _user, address _to, uint256 _newCumLiqForClaims, bytes32[] calldata _liqForClaimsProof, uint256 _newPercentReserved, bytes32[] calldata _percentReservedProof ) external onlyShield returns (bool) { _update(_newCumLiqForClaims, _liqForClaimsProof, _newPercentReserved, _percentReservedProof, true); emit RedeemFinalize(msg.sender, _user, block.timestamp); return isRouterVerified[_to]; } /** * @notice Updates contract, emits event for purchase action, verifies price. * @param _user The user that is making the purchase. * @param _uToken The user that is making the purchase. * @param _ethPrice The price of one token in Ether. * @param _priceProof Merkle proof to verify the Ether price of the token. * @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed. * @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed. */ function purchase( address _user, address _uToken, uint256 _ethPrice, bytes32[] calldata _priceProof, uint256 _newCumLiqForClaims, bytes32[] calldata _liqForClaimsProof ) external onlyShield { _update(_newCumLiqForClaims, _liqForClaimsProof, 0, new bytes32[](0), false); verifyPrice(_uToken, _ethPrice, _priceProof); emit Purchase(msg.sender, _user, block.timestamp); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////// internal ////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice All general updating of shields for a variety of variables that could have changed * since the last interaction. Amount for sale, whether or not the system is paused, new * withdrawal delay, new discount for sales, new APR fee for general functionality. * @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed. * @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed. * @param _newPercentReserved New percent of tokens of this shield that are reserved. * @param _percentReservedProof Merkle proof to verify the new percent reserved. * @param _redeem Whether or not this is a redeem request to know whether to update reserved. */ function _update( uint256 _newCumLiqForClaims, bytes32[] memory _liqForClaimsProof, uint256 _newPercentReserved, bytes32[] memory _percentReservedProof, bool _redeem ) internal { IRcaShield shield = IRcaShield(msg.sender); uint32 lastUpdate = uint32(lastShieldUpdate[msg.sender]); // Seems kinda messy but not too bad on gas. SystemUpdates memory updates = systemUpdates; if (lastUpdate <= updates.treasuryUpdate) shield.setTreasury(treasury); if (lastUpdate <= updates.discountUpdate) shield.setDiscount(discount); if (lastUpdate <= updates.withdrawalDelayUpdate) shield.setWithdrawalDelay(withdrawalDelay); // Update shield here to account for interim period where APR was changed but shield had not updated. if (lastUpdate <= updates.aprUpdate) { shield.controllerUpdate(apr, uint256(updates.aprUpdate)); shield.setApr(apr); } if (lastUpdate <= updates.liqUpdate) { // Update potentially needed here as well if amtForSale will grow from APR. shield.controllerUpdate(apr, uint256(updates.aprUpdate)); verifyLiq(msg.sender, _newCumLiqForClaims, _liqForClaimsProof); shield.setLiqForClaims(_newCumLiqForClaims); } // Only updates if it's a redeem request (which is the only call that's affected by reserved). if (lastUpdate <= updates.reservedUpdate && _redeem) { verifyReserved(msg.sender, _newPercentReserved, _percentReservedProof); shield.setPercentReserved(_newPercentReserved); } lastShieldUpdate[msg.sender] = uint32(block.timestamp); } /** * @notice Verify the signature approving the transaction. * @param _user User that is being minted to. * @param _amount Amount of underlying tokens being deposited. * @param _expiry Time (Unix timestamp) that this request expires. * @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 verifyCapacitySig( address _user, uint256 _amount, uint256 _expiry, uint8 _v, bytes32 _r, bytes32 _s ) internal { bytes32 digest = keccak256( abi.encodePacked( "EASE_RCA_CONTROLLER_1.0", block.chainid, address(this), _user, msg.sender, _amount, nonces[_user]++, _expiry ) ); bytes32 message = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", digest)); address signatory = ecrecover(message, _v, _r, _s); require(signatory == capOracle, "Invalid capacity oracle signature."); require(block.timestamp <= _expiry, "Capacity permission has expired."); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////// view //////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Verify the current amount for liquidation. * @param _shield Address of the shield to verify. * @param _newCumLiqForClaims New cumulative amount liquidated. * @param _liqForClaimsProof Proof of the for sale amounts. */ function verifyLiq( address _shield, uint256 _newCumLiqForClaims, bytes32[] memory _liqForClaimsProof ) public view { bytes32 leaf = keccak256(abi.encodePacked(_shield, _newCumLiqForClaims)); require(MerkleProof.verify(_liqForClaimsProof, liqForClaimsRoot, leaf), "Incorrect liq proof."); } /** * @notice Verify price from Ease price oracle. * @param _shield Address of the shield to find price of. * @param _value Price of the underlying token (in Ether) for this shield. * @param _proof Merkle proof. */ function verifyPrice( address _shield, uint256 _value, bytes32[] memory _proof ) public view { bytes32 leaf = keccak256(abi.encodePacked(_shield, _value)); // This doesn't protect against oracle hacks, but does protect against some bugs. require(_value > 0, "Invalid price submitted."); require(MerkleProof.verify(_proof, priceRoot, leaf), "Incorrect price proof."); } /** * @notice Verify the percent reserved for a particular shield. * @param _shield Address of the shield/token to verify reserved. * @param _percentReserved Percent of shield that's reserved. 10% == 1000. * @param _proof The Merkle proof verifying the percent reserved. */ function verifyReserved( address _shield, uint256 _percentReserved, bytes32[] memory _proof ) public view { bytes32 leaf = keccak256(abi.encodePacked(_shield, _percentReserved)); require(MerkleProof.verify(_proof, reservedRoot, leaf), "Incorrect capacity proof."); } /** * @notice Makes it easier for frontend to get the balances on many shields. * @param _user User to find balances of. * @param _tokens The shields (also tokens) to find the RCA balances for. */ function balanceOfs(address _user, address[] calldata _tokens) external view returns (uint256[] memory balances) { balances = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { uint256 balance = IERC20(_tokens[i]).balanceOf(_user); balances[i] = balance; } } /** * @notice Makes it easier for frontend to get the currently withdrawing requests for each shield. * @param _user User to find requests of. * @param _shields The shields to find the request data for. */ function requestOfs( address _user, address[] calldata _shields ) external view returns (IRcaShield.WithdrawRequest[] memory requests) { requests = new IRcaShield.WithdrawRequest[](_shields.length); for (uint256 i = 0; i < _shields.length; i++) { IRcaShield.WithdrawRequest memory request = IRcaShield(_shields[i]).withdrawRequests(_user); requests[i] = request; } } /** * @notice Used by frontend to craft signature for a requested transaction. * @param _user User that is being minted to. * @param _shield Address of the shield that tokens are being deposited into. * @param _amount Amount of underlying tokens to deposit. * @param _nonce User nonce (current nonce +1) that this transaction will be. * @param _expiry Time (Unix timestamp) that this request will expire. */ function getMessageHash( address _user, address _shield, uint256 _amount, uint256 _nonce, uint256 _expiry ) external view returns (bytes32) { return keccak256( abi.encodePacked( "EASE_RCA_CONTROLLER_1.0", block.chainid, address(this), _user, _shield, _amount, _nonce, _expiry ) ); } function getAprUpdate() external view returns (uint32) { return systemUpdates.aprUpdate; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////// onlyGov ////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Initialize a new shield. * @param _shield Address of the shield to initialize. */ function initializeShield(address _shield) external onlyGov { IRcaShield(_shield).initialize(apr, discount, treasury, withdrawalDelay); shieldMapping[_shield] = true; activeShields[_shield] = true; lastShieldUpdate[_shield] = block.timestamp; emit ShieldCreated( _shield, address(IRcaShield(_shield).uToken()), IRcaShield(_shield).name(), IRcaShield(_shield).symbol(), block.timestamp ); } /** * @notice Governance calls to set the new total amount for sale. * @param _newLiqRoot Merkle root for new total amounts for sale for each protocol (in token). * @param _newReservedRoot Reserved root setting all percent reserved back to 0. */ function setLiqTotal(bytes32 _newLiqRoot, bytes32 _newReservedRoot) external onlyGov { liqForClaimsRoot = _newLiqRoot; systemUpdates.liqUpdate = uint32(block.timestamp); reservedRoot = _newReservedRoot; systemUpdates.reservedUpdate = uint32(block.timestamp); } /** * @notice Governance can reset withdrawal delay for amount of time it takes to withdraw from vaults. * Not a commonly used function, if at all really. * @param _newWithdrawalDelay New delay (in seconds) for withdrawals. */ function setWithdrawalDelay(uint256 _newWithdrawalDelay) external onlyGov { require(_newWithdrawalDelay <= 86400 * 7, "Withdrawal delay may not be more than 7 days."); withdrawalDelay = _newWithdrawalDelay; systemUpdates.withdrawalDelayUpdate = uint32(block.timestamp); } /** * @notice Governance can change the amount of discount for purchasing tokens that are being liquidated. * @param _newDiscount New discount for purchase in tenths of a percent (1000 == 10%). */ function setDiscount(uint256 _newDiscount) external onlyGov { require(_newDiscount <= 2500, "Discount may not be more than 25%."); discount = _newDiscount; systemUpdates.discountUpdate = uint32(block.timestamp); } /** * @notice Governance can set the fees taken per year from a vault. Starts at 0, can update at any time. * @param _newApr New fees per year for being in the RCA system (1000 == 10%). */ function setApr(uint256 _newApr) external onlyGov { require(_newApr <= 2000, "APR may not be more than 20%."); apr = _newApr; systemUpdates.aprUpdate = uint32(block.timestamp); } /** * @notice Governance can set address of the new treasury contract that accepts funds. * @param _newTreasury New fees per year for being in the RCA system (1000 == 10%). */ function setTreasury(address payable _newTreasury) external onlyGov { treasury = _newTreasury; systemUpdates.treasuryUpdate = uint32(block.timestamp); } /** * @notice Governance can cancel the shield support. * @param _shields An array of shield addresses that are being cancelled. */ function cancelShield(address[] memory _shields) external onlyGov { for (uint256 i = 0; i < _shields.length; i++) { activeShields[_shields[i]] = false; emit ShieldCancelled(_shields[i]); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// onlyGuardian /////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Admin can set the percent paused. This pauses this percent of tokens from each shield * while the DAO analyzes losses. If a withdrawal occurs while reserved > 0, * the user will lose this percent of tokens. * @param _newReservedRoot Percent of shields to temporarily pause for each shield. 1000 == 10%. */ function setPercentReserved(bytes32 _newReservedRoot) external onlyGuardian { reservedRoot = _newReservedRoot; systemUpdates.reservedUpdate = uint32(block.timestamp); } /** * @notice Admin can set which router is verified and which is not. * @param _routerAddress Address of a router. * @param _verified New verified status of the router. */ function setRouterVerified(address _routerAddress, bool _verified) external onlyGuardian { isRouterVerified[_routerAddress] = _verified; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////// onlyPriceOracle ////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Set prices of all tokens with our oracle. This will likely be expanded so that price oracle is a * smart contract that accepts input from a few sources to increase decentralization. * @param _newPriceRoot Merkle root for new prices of each underlying token in * Ether (key is shield address or token for rewards). */ function setPrices(bytes32 _newPriceRoot) external onlyPriceOracle { priceRoot = _newPriceRoot; } } /// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.11; import "../general/Governable.sol"; /** * @title Governable * @dev Pretty default ownable but with variable names changed to better convey owner. */ contract RcaGovernable is Governable { address public guardian; address public priceOracle; address public capOracle; event NewGuardian(address indexed oldGuardian, address indexed newGuardian); event NewPriceOracle(address indexed oldOracle, address indexed newOracle); event NewCapOracle(address indexed oldOracle, address indexed newOracle); /** * @dev The Ownable constructor sets the original s of the contract to the sender * account. */ function initRcaGovernable( address _governor, address _guardian, address _capOracle, address _priceOracle ) internal { require(governor() == address(0), "already initialized"); initializeGovernable(_governor); guardian = _guardian; capOracle = _capOracle; priceOracle = _priceOracle; emit NewGuardian(address(0), _guardian); emit NewCapOracle(address(0), _capOracle); emit NewPriceOracle(address(0), _priceOracle); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGuardian() { require(msg.sender == guardian, "msg.sender is not Guardian."); _; } modifier onlyPriceOracle() { require(msg.sender == priceOracle, "msg.sender is not price oracle."); _; } modifier onlyCapOracle() { require(msg.sender == capOracle, "msg.sender is not capacity oracle."); _; } /** * @notice Allows the current owner to transfer control of the contract to a newOwner. * @param _newGuardian The address to transfer ownership to. */ function setGuardian(address _newGuardian) public onlyGov { guardian = _newGuardian; } function setPriceOracle(address _newPriceOracle) public onlyGov { priceOracle = _newPriceOracle; } function setCapOracle(address _newCapOracle) public onlyGov { capOracle = _newCapOracle; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } /// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRcaShield { function setApr(uint256 apr) external; function setTreasury(address treasury) external; function setDiscount(uint256 discount) external; function setLiqForClaims(uint256 addForSale) external; function setPercentReserved(uint256 percentPaused) external; function setWithdrawalDelay(uint256 withdrawalDelay) external; function initialize( uint256 apr, uint256 discount, address treasury, uint256 withdrawalDelay ) external; function name() external returns (string calldata); function symbol() external returns (string calldata); function uToken() external returns (IERC20); function controllerUpdate(uint256 apr, uint256 aprUpdate) external; struct WithdrawRequest { uint112 uAmount; uint112 rcaAmount; uint32 endTime; } function withdrawRequests(address user) external view returns (WithdrawRequest memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; /** * @title Governable * @dev Pretty default ownable but with variable names changed to better convey owner. */ contract Governable { address payable private _governor; address payable private _pendingGovernor; event OwnershipTransferred(address indexed previousGovernor, address indexed newGovernor); event PendingOwnershipTransfer(address indexed from, address indexed to); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initializeGovernable(address _newGovernor) internal { require(_governor == address(0), "already initialized"); _governor = payable(_newGovernor); emit OwnershipTransferred(address(0), _newGovernor); } /** * @return the address of the owner. */ function governor() public view returns (address payable) { return _governor; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGov() { require(isGov(), "msg.sender is not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isGov() public view returns (bool) { return msg.sender == _governor; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newGovernor The address to transfer ownership to. */ function transferOwnership(address payable newGovernor) public onlyGov { _pendingGovernor = newGovernor; emit PendingOwnershipTransfer(_governor, newGovernor); } function receiveOwnership() public { require(msg.sender == _pendingGovernor, "Only pending governor can call this function"); _transferOwnership(_pendingGovernor); _pendingGovernor = payable(address(0)); } /** * @dev Transfers control of the contract to a newOwner. * @param newGovernor The address to transfer ownership to. */ function _transferOwnership(address payable newGovernor) internal { require(newGovernor != address(0)); emit OwnershipTransferred(_governor, newGovernor); _governor = newGovernor; } uint256[50] private __gap; }
Updates contract, emits event for redeem action. _user User that is redeeming tokens. _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed. _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed. _newPercentReserved New percent of the shield that is reserved for hack payouts. _percentReservedProof Merkle proof to verify the new percent reserved./
function redeemRequest( address _user, uint256 _newCumLiqForClaims, bytes32[] calldata _liqForClaimsProof, uint256 _newPercentReserved, bytes32[] calldata _percentReservedProof ) external onlyShield { _update(_newCumLiqForClaims, _liqForClaimsProof, _newPercentReserved, _percentReservedProof, true); emit RedeemRequest(msg.sender, _user, block.timestamp); }
10,309,561
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC20 { function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool); function mint (address _to, uint256 _amount) external returns (bool); } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract Crowdsale is Ownable { using SafeMath for uint256; modifier onlyWhileOpen { require( (now >= preICOStartDate && now < preICOEndDate) || (now >= ICOStartDate && now < ICOEndDate) ); _; } modifier onlyWhileICOOpen { require(now >= ICOStartDate && now < ICOEndDate); _; } // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Бколько Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² ΠΏΠΎΠΊΡƒΠΏΠ°Ρ‚Π΅Π»ΡŒ ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ Π·Π° 1 эфир uint256 public rate = 1000; // Бколько эфиров ΠΏΡ€ΠΈΠ²Π»Π΅Ρ‡Π΅Π½ΠΎ Π² Ρ…ΠΎΠ΄Π΅ PreICO, wei uint256 public preICOWeiRaised; // Бколько эфиров ΠΏΡ€ΠΈΠ²Π»Π΅Ρ‡Π΅Π½ΠΎ Π² Ρ…ΠΎΠ΄Π΅ ICO, wei uint256 public ICOWeiRaised; // Π¦Π΅Π½Π° ETH Π² Ρ†Π΅Π½Ρ‚Π°Ρ… uint256 public ETHUSD; // Π”Π°Ρ‚Π° Π½Π°Ρ‡Π°Π»Π° PreICO uint256 public preICOStartDate; // Π”Π°Ρ‚Π° окончания PreICO uint256 public preICOEndDate; // Π”Π°Ρ‚Π° Π½Π°Ρ‡Π°Π»Π° ICO uint256 public ICOStartDate; // Π”Π°Ρ‚Π° окончания ICO uint256 public ICOEndDate; // ΠœΠΈΠ½ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹ΠΉ объСм привлСчСния срСдств Π² Ρ…ΠΎΠ΄Π΅ ICO Π² Ρ†Π΅Π½Ρ‚Π°Ρ… uint256 public softcap = 300000000; // ΠŸΠΎΡ‚ΠΎΠ»ΠΎΠΊ привлСчСния срСдств Π² Ρ…ΠΎΠ΄Π΅ ICO Π² Ρ†Π΅Π½Ρ‚Π°Ρ… uint256 public hardcap = 2500000000; // Бонус Ρ€Π΅Ρ„Π΅Ρ€Π°Π»Π°, % uint8 public referalBonus = 3; // Бонус ΠΏΡ€ΠΈΠ³Π»Π°ΡˆΠ΅Π½Π½ΠΎΠ³ΠΎ Ρ€Π΅Ρ„Π΅Ρ€Π°Π»ΠΎΠΌ, % uint8 public invitedByReferalBonus = 2; // Whitelist mapping(address => bool) public whitelist; // Π˜Π½Π²Π΅ΡΡ‚ΠΎΡ€Ρ‹, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΊΡƒΠΏΠΈΠ»ΠΈ Ρ‚ΠΎΠΊΠ΅Π½ mapping (address => uint256) public investors; event TokenPurchase(address indexed buyer, uint256 value, uint256 amount); function Crowdsale( address _wallet, uint256 _preICOStartDate, uint256 _preICOEndDate, uint256 _ICOStartDate, uint256 _ICOEndDate, uint256 _ETHUSD ) public { require(_preICOEndDate > _preICOStartDate); require(_ICOStartDate > _preICOEndDate); require(_ICOEndDate > _ICOStartDate); wallet = _wallet; preICOStartDate = _preICOStartDate; preICOEndDate = _preICOEndDate; ICOStartDate = _ICOStartDate; ICOEndDate = _ICOEndDate; ETHUSD = _ETHUSD; } /* ΠŸΡƒΠ±Π»ΠΈΡ‡Π½Ρ‹Π΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹ */ // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ ΡΡ‚ΠΎΠΈΠΌΠΎΡΡ‚ΡŒ Ρ‚ΠΎΠΊΠ΅Π½Π° function setRate (uint16 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ адрСс кошСлька для сбора срСдств function setWallet (address _wallet) public onlyOwner { require (_wallet != 0x0); wallet = _wallet; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Ρ‚ΠΎΡ€Π³ΡƒΠ΅ΠΌΡ‹ΠΉ Ρ‚ΠΎΠΊΠ΅Π½ function setToken (ERC20 _token) public onlyOwner { token = _token; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π΄Π°Ρ‚Ρƒ Π½Π°Ρ‡Π°Π»Π° PreICO function setPreICOStartDate (uint256 _preICOStartDate) public onlyOwner { require(_preICOStartDate < preICOEndDate); preICOStartDate = _preICOStartDate; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π΄Π°Ρ‚Ρƒ окончания PreICO function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner { require(_preICOEndDate > preICOStartDate); preICOEndDate = _preICOEndDate; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π΄Π°Ρ‚Ρƒ Π½Π°Ρ‡Π°Π»Π° ICO function setICOStartDate (uint256 _ICOStartDate) public onlyOwner { require(_ICOStartDate < ICOEndDate); ICOStartDate = _ICOStartDate; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π΄Π°Ρ‚Ρƒ окончания PreICO function setICOEndDate (uint256 _ICOEndDate) public onlyOwner { require(_ICOEndDate > ICOStartDate); ICOEndDate = _ICOEndDate; } // Π£ΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ ΡΡ‚ΠΎΠΈΠΌΠΎΡΡ‚ΡŒ эфира Π² Ρ†Π΅Π½Ρ‚Π°Ρ… function setETHUSD (uint256 _ETHUSD) public onlyOwner { ETHUSD = _ETHUSD; } function () external payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; uint256 tokens; if(_isPreICO()){ _preValidatePreICOPurchase(beneficiary, weiAmount); tokens = weiAmount.mul(rate.add(rate.mul(30).div(100))); preICOWeiRaised = preICOWeiRaised.add(weiAmount); wallet.transfer(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); TokenPurchase(beneficiary, weiAmount, tokens); } else if(_isICO()){ _preValidateICOPurchase(beneficiary, weiAmount); tokens = _getTokenAmountWithBonus(weiAmount); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); TokenPurchase(beneficiary, weiAmount, tokens); } } // ΠŸΠΎΠΊΡƒΠΏΠΊΠ° Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² с Ρ€Π΅Ρ„Π΅Ρ€Π°Π»ΡŒΠ½Ρ‹ΠΌ бонусом function buyTokensWithReferal(address _referal) public onlyWhileICOOpen payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; _preValidateICOPurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmountWithBonus(weiAmount).add(_getTokenAmountWithReferal(weiAmount, 2)); uint256 referalTokens = _getTokenAmountWithReferal(weiAmount, 3); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); _deliverTokens(_referal, referalTokens); TokenPurchase(beneficiary, weiAmount, tokens); } // Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ адрСс Π² whitelist function addToWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = true; } // Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ нСсколько адрСсов Π² whitelist function addManyToWhitelist(address[] _beneficiaries) public onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } // Π˜ΡΠΊΠ»ΡŽΡ‡ΠΈΡ‚ΡŒ адрСс ΠΈΠ· whitelist function removeFromWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = false; } // Π£Π·Π½Π°Ρ‚ΡŒ истСк Π»ΠΈ срок провСдСния PreICO function hasPreICOClosed() public view returns (bool) { return now > preICOEndDate; } // Π£Π·Π½Π°Ρ‚ΡŒ истСк Π»ΠΈ срок провСдСния ICO function hasICOClosed() public view returns (bool) { return now > ICOEndDate; } // ΠŸΠ΅Ρ€Π΅Π²Π΅ΡΡ‚ΠΈ собранныС срСдства Π½Π° кошСлСк для сбора function forwardFunds () public onlyOwner { require(now > ICOEndDate); require((preICOWeiRaised.add(ICOWeiRaised)).mul(ETHUSD).div(10**18) >= softcap); wallet.transfer(ICOWeiRaised); } // Π’Π΅Ρ€Π½ΡƒΡ‚ΡŒ проинвСстированныС срСдства, Ссли Π½Π΅ Π±Ρ‹Π» достигнут softcap function refund() public { require(now > ICOEndDate); require(preICOWeiRaised.add(ICOWeiRaised).mul(ETHUSD).div(10**18) < softcap); require(investors[msg.sender] > 0); address investor = msg.sender; investor.transfer(investors[investor]); } /* Π’Π½ΡƒΡ‚Ρ€Π΅Π½Π½ΠΈΠ΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹ */ // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ PreICO function _isPreICO() internal view returns(bool) { return now >= preICOStartDate && now < preICOEndDate; } // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ ICO function _isICO() internal view returns(bool) { return now >= ICOStartDate && now < ICOEndDate; } // Валидация ΠΏΠ΅Ρ€Π΅Π΄ ΠΏΠΎΠΊΡƒΠΏΠΊΠΎΠΉ Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² function _preValidatePreICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(now >= preICOStartDate && now <= preICOEndDate); } function _preValidateICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require((preICOWeiRaised + ICOWeiRaised + _weiAmount).mul(ETHUSD).div(10**18) <= hardcap); require(now >= ICOStartDate && now <= ICOEndDate); } // ΠŸΠΎΠ΄ΡΡ‡Π΅Ρ‚ бонусов с ΡƒΡ‡Π΅Ρ‚ΠΎΠΌ бонусов Π·Π° этап ICO ΠΈ объСм инвСстиций function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256) { uint256 baseTokenAmount = _weiAmount.mul(rate); uint256 tokenAmount = baseTokenAmount; uint256 usdAmount = _weiAmount.mul(ETHUSD).div(10**18); // Π‘Ρ‡ΠΈΡ‚Π°Π΅ΠΌ бонусы Π·Π° объСм инвСстиций if(usdAmount >= 10000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(7).div(100)); } else if(usdAmount >= 5000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } else if(usdAmount >= 1000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(3).div(100)); } // Π‘Ρ‡ΠΈΡ‚Π°Π΅ΠΌ бонусы Π·Π° этап ICO if(now < ICOStartDate + 15 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(20).div(100)); } else if(now < ICOStartDate + 28 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(15).div(100)); } else if(now < ICOStartDate + 42 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(10).div(100)); } else { tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } return tokenAmount; } // ΠŸΠΎΠ΄ΡΡ‡Π΅Ρ‚ бонусов с ΡƒΡ‡Π΅Ρ‚ΠΎΠΌ бонусов Ρ€Π΅Ρ„Π΅Ρ€Π°Π»ΡŒΠ½ΠΎΠΉ систСмы function _getTokenAmountWithReferal(uint256 _weiAmount, uint8 _percent) internal view returns(uint256) { return _weiAmount.mul(rate).mul(_percent).div(100); } // ΠŸΠ΅Ρ€Π΅Π²ΠΎΠ΄ Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.mint(_beneficiary, _tokenAmount); } }
Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ адрСс Π² whitelist
function addToWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = true; }
15,055,611
./full_match/1/0xAc096F8abCd44A346ad0eA6Df4Ccde52160837A6/sources/contracts/Lottery/SpacecowsLottery.sol
Get all user owned tickets by lottery id _lotteryId: lottery id _player: user address/
function playerTicketsByLottery(uint256 _lotteryId, address _player) external view returns (uint32[] memory) { Lottery memory currentLottery = _lotteries[_lotteryId]; uint256 index = 0; uint256 ticketCount = _playerTicketCountByLottery(_lotteryId, _player); uint32[] memory tickets = new uint32[](ticketCount); for (uint256 i = 0; i < currentLottery.ticketId; ++i) { Player memory tmpPlayer = _tickets[_lotteryId][i]; if (tmpPlayer.owner == _player) { for (uint32 j = tmpPlayer.ticketStart; j <= tmpPlayer.ticketEnd; ++j) { tickets[index] = j; ++index; } } } return tickets; }
17,102,656
//Address: 0xdba3c9f9a427d2bdb7e260353dce57a94cd8ddd8 //Contract name: Zorro02Token //Balance: 0 Ether //Verification Date: 8/15/2017 //Transacion Count: 9 // CODE STARTS HERE pragma solidity ^0.4.11; // ---------------------------------------------------------------------------- // // Owned contract // // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferProposed( address indexed _from, address indexed _to ); event OwnershipTransferred( address indexed _from, address indexed _to ); function Owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner { require(_newOwner != address(0x0)); OwnershipTransferProposed(owner, _newOwner); newOwner = _newOwner; } function acceptOwnership() { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ---------------------------------------------------------------------------- // // SafeMath contract // // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); uint c = a - b; assert(c <= a); return c; } } // ---------------------------------------------------------------------------- // // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 // // ---------------------------------------------------------------------------- contract ERC20Interface { event LogTransfer( address indexed _from, address indexed _to, uint256 _value ); event LogApproval( address indexed _owner, address indexed _spender, uint256 _value ); function totalSupply() constant returns (uint256); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } // ---------------------------------------------------------------------------- // // ERC Token Standard #20 // // note that totalSupply() is not defined here // // ---------------------------------------------------------------------------- contract ERC20Token is ERC20Interface, Owned, SafeMath { // Account balances // mapping(address => uint256) balances; // Account holder approves the transfer of an amount to another account // mapping(address => mapping (address => uint256)) allowed; // Get the account balance for an address function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer the balance from owner's account to another account // ------------------------------------------------------------------------ function transfer(address _to, uint256 _amount) returns (bool success) { require( _amount > 0 ); // Non-zero transfer require( balances[msg.sender] >= _amount ); // User has balance require( balances[_to] + _amount > balances[_to] ); // Overflow check balances[msg.sender] -= _amount; balances[_to] += _amount; LogTransfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------------------------------ // Allow _spender to withdraw from your account, multiple times, up to // _amount. If this function is called again it overwrites the // current allowance with _amount. // ------------------------------------------------------------------------ function approve(address _spender, uint256 _amount) returns (bool success) { // before changing the approve amount for an address, its allowance // must be reset to 0 to mitigate the race condition described here: // cf https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require( _amount == 0 || allowed[msg.sender][_spender] == 0 ); // the approval amount cannot exceed the balance require (balances[msg.sender] >= _amount); allowed[msg.sender][_spender] = _amount; LogApproval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner's // balance to another account. The owner of the tokens must already // have approve(...)-d this transfer // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { require( _amount > 0 ); // Non-zero transfer require( balances[_from] >= _amount ); // Sufficient balance require( allowed[_from][msg.sender] >= _amount ); // Transfer approved require( balances[_to] + _amount > balances[_to] ); // Overflow check balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; LogTransfer(_from, _to, _amount); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred by _spender // ------------------------------------------------------------------------ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } // ---------------------------------------------------------------------------- // // GZR public token sale // // ---------------------------------------------------------------------------- contract Zorro02Token is ERC20Token { // VARIABLES ================================ // basic token data string public constant name = "Zorro02"; string public constant symbol = "ZORRO02"; uint8 public constant decimals = 18; string public constant GITHUB_LINK = 'htp://github.com/..'; // wallet address (can be reset at any time during ICO) address public wallet; // ICO variables that can be reset before ICO starts uint public tokensPerEth = 100000; uint public icoTokenSupply = 300; // ICO constants #1 uint public constant TOTAL_TOKEN_SUPPLY = 1000; uint public constant ICO_TRIGGER = 10; uint public constant MIN_CONTRIBUTION = 10**15; // ICO constants #2 : ICO dates // Start - Friday, 15-Sep-17 00:00:00 UTC // End - Sunday, 15-Oct-17 00:00:00 UTC // as per http://www.unixtimestamp.com uint public constant START_DATE = 1502787600; uint public constant END_DATE = 1502791200; // ICO variables uint public icoTokensIssued = 0; bool public icoFinished = false; bool public tradeable = false; // Minting uint public ownerTokensMinted = 0; // other variables uint256 constant MULT_FACTOR = 10**18; // EVENTS =================================== event LogWalletUpdated( address newWallet ); event LogTokensPerEthUpdated( uint newTokensPerEth ); event LogIcoTokenSupplyUpdated( uint newIcoTokenSupply ); event LogTokensBought( address indexed buyer, uint ethers, uint tokens, uint participantTokenBalance, uint newIcoTokensIssued ); event LogMinting( address indexed participant, uint tokens, uint newOwnerTokensMinted ); // FUNCTIONS ================================ // -------------------------------- // initialize // -------------------------------- function Zorro02Token() { owner = msg.sender; wallet = msg.sender; } // -------------------------------- // implement totalSupply() ERC20 function // -------------------------------- function totalSupply() constant returns (uint256) { return TOTAL_TOKEN_SUPPLY; } // -------------------------------- // changing ICO parameters // -------------------------------- // Owner can change the crowdsale wallet address at any time // function setWallet(address _wallet) onlyOwner { wallet = _wallet; LogWalletUpdated(wallet); } // Owner can change the number of tokens per ETH before the ICO start date // function setTokensPerEth(uint _tokensPerEth) onlyOwner { require(now < START_DATE); require(_tokensPerEth > 0); tokensPerEth = _tokensPerEth; LogTokensPerEthUpdated(tokensPerEth); } // Owner can change the number available tokens for the ICO // (must be below 70 million) // function setIcoTokenSupply(uint _icoTokenSupply) onlyOwner { require(now < START_DATE); require(_icoTokenSupply < TOTAL_TOKEN_SUPPLY); icoTokenSupply = _icoTokenSupply; LogIcoTokenSupplyUpdated(icoTokenSupply); } // -------------------------------- // Default function // -------------------------------- function () payable { proxyPayment(msg.sender); } // -------------------------------- // Accept ETH during crowdsale // -------------------------------- function proxyPayment(address participant) payable { require(!icoFinished); require(now >= START_DATE); require(now <= END_DATE); require(msg.value > MIN_CONTRIBUTION); // get number of tokens uint tokens = msg.value * tokensPerEth; // first check if there is enough capacity uint available = icoTokenSupply - icoTokensIssued; require (tokens <= available); // ok it's possible to issue tokens so let's do it // Add tokens purchased to account's balance and total supply // TODO - verify SafeAdd is not necessary balances[participant] += tokens; icoTokensIssued += tokens; // Transfer the tokens to the participant LogTransfer(0x0, participant, tokens); // Log the token purchase LogTokensBought(participant, msg.value, tokens, balances[participant], icoTokensIssued); // Transfer the contributed ethers to the crowdsale wallet // throw is deprecated starting from Ethereum v0.9.0 wallet.transfer(msg.value); } // -------------------------------- // Minting of tokens by owner // -------------------------------- // Tokens remaining available to mint by owner // function availableToMint() returns (uint) { if (icoFinished) { return TOTAL_TOKEN_SUPPLY - icoTokensIssued - ownerTokensMinted; } else { return TOTAL_TOKEN_SUPPLY - icoTokenSupply - ownerTokensMinted; } } // Minting of tokens by owner // function mint(address participant, uint256 tokens) onlyOwner { require( tokens <= availableToMint() ); balances[participant] += tokens; ownerTokensMinted += tokens; LogTransfer(0x0, participant, tokens); LogMinting(participant, tokens, ownerTokensMinted); } // -------------------------------- // Declare ICO finished // -------------------------------- function declareIcoFinished() onlyOwner { // the token can only be made tradeable after ICO finishes require( now > END_DATE || icoTokenSupply - icoTokensIssued < ICO_TRIGGER ); icoFinished = true; } // -------------------------------- // Make tokens tradeable // -------------------------------- function tradeable() onlyOwner { // the token can only be made tradeable after ICO finishes require(icoFinished); tradeable = true; } // -------------------------------- // Transfers // -------------------------------- function transfer(address _to, uint _amount) returns (bool success) { // Cannot transfer out until tradeable, except for owner require(tradeable || msg.sender == owner); return super.transfer(_to, _amount); } function transferFrom(address _from, address _to, uint _amount) returns (bool success) { // not possible until tradeable require(tradeable); return super.transferFrom(_from, _to, _amount); } // -------------------------------- // Varia // -------------------------------- // Transfer out any accidentally sent ERC20 tokens function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, amount); } }
get number of tokens first check if there is enough capacity ok it's possible to issue tokens so let's do it Add tokens purchased to account's balance and total supply TODO - verify SafeAdd is not necessary Transfer the tokens to the participant Log the token purchase Transfer the contributed ethers to the crowdsale wallet throw is deprecated starting from Ethereum v0.9.0
function proxyPayment(address participant) payable { require(!icoFinished); require(now >= START_DATE); require(now <= END_DATE); require(msg.value > MIN_CONTRIBUTION); uint tokens = msg.value * tokensPerEth; uint available = icoTokenSupply - icoTokensIssued; require (tokens <= available); balances[participant] += tokens; icoTokensIssued += tokens; LogTransfer(0x0, participant, tokens); LogTokensBought(participant, msg.value, tokens, balances[participant], icoTokensIssued); wallet.transfer(msg.value); }
13,075,523
pragma solidity ^0.4.18; // File: contracts/ERC721Draft.sol /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } // File: contracts/Auction/ClockAuctionBase.sol /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev DON'T give me your money. function() external {} // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= 18446744073709551615); _; } modifier canBeStoredWith128Bits(uint256 _value) { require(_value < 340282366920938463463374607431768211455); _; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the incoming bid is higher than the current // price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } // 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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } // File: contracts/Auction/ClockAuction.sol /// @title Clock auction for non-fungible tokens. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.implementsERC721()); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); nftAddress.transfer(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public whenNotPaused canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) public payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) public view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } // File: contracts/Auction/SaleClockAuction.sol /// @title Clock auction modified for sale of kitties contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 kitty sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) public payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() public view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } // File: contracts/Auction/SiringClockAuction.sol /// @title Reverse auction modified for siring contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the KittyCore contract because all bid methods /// should be wrapped. Also returns the kitty to the /// seller rather than the winner. function bid(uint256 _tokenId) public payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the kitty back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } // File: contracts/ExternalInterfaces/GeneScienceInterface.sol /// @title defined the interface that will be referenced in main Kitty contract contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2) public returns (uint256); } // File: contracts/KittyAccessControl.sol /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyAccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function withdrawBalance() external onlyCFO { cfoAddress.transfer(this.balance); } /*** 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 Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() public onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } // File: contracts/KittyBase.sol /// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBase is KittyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address indexed owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /*** DATA TYPES ***/ /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Kitty { // The Kitty's genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat's genes never change. uint256 genes; // The timestamp from the block when this cat came into existence. uint64 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndTime; // The ID of the parents of this kitty, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Kitty. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; /*** STORAGE ***/ /// @dev An array containing the Kitty struct for all Kitties in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Kitty[] kitties; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) public kittyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KittyIDs to an address that has been approved to call /// transferFrom(). Each Kitty can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public kittyIndexToApproved; /// @dev A mapping from KittyIDs to an address that has been approved to use /// this Kitty for siring via breedWith(). Each Kitty can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev Assigns ownership of a specific Kitty to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of kittens is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership kittyIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete kittyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new kitty and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The kitty's genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKitty() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId <= 4294967295); require(_sireId <= 4294967295); require(_generation <= 65535); Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndTime: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: 0, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; // It's probably never going to happen, 4 billion cats is A LOT, but // let's just be 100% sure we never let this happen. require(newKittenId <= 4294967295); // emit the birth event Birth( _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newKittenId); return newKittenId; } } // File: contracts/KittyOwnership.sol /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyOwnership is KittyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public name = "CryptoKitties"; string public symbol = "CK"; // bool public implementsERC721 = true; // function implementsERC721() public pure returns (bool) { return true; } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Kitty. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Kitty. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// @dev Transfers a kitty owned by this contract to the specified address. /// Used to rescue lost kitties. (There is no "proper" flow where this contract /// should be the owner of any Kitty. This function exists for us to reassign /// the ownership of Kitties that users may have accidentally sent to our address.) /// @param _kittyId - ID of kitty /// @param _recipient - Address to send the cat to function rescueLostKitty(uint256 _kittyId, address _recipient) public onlyCOO whenNotPaused { require(_owns(this, _kittyId)); _transfer(this, _recipient, _kittyId); } /// @notice Returns the number of Kitties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Kitty to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Kitty to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Kitty via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Kitty owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Kitty to be transfered. /// @param _to The address that should take ownership of the Kitty. Can be any address, /// including the caller. /// @param _tokenId The ID of the Kitty to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Kitties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return kitties.length - 1; } /// @notice Returns the address currently assigned ownership of a given Kitty. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns the nth Kitty assigned to an address, with n specified by the /// _index argument. /// @param _owner The owner whose Kitties we are interested in. /// @param _index The zero-based index of the cat within the owner's list of cats. /// Must be less than balanceOf(_owner). /// @dev This method MUST NEVER be called by smart contract code. It will almost /// certainly blow past the block gas limit once there are a large number of /// Kitties in existence. Exists only to allow off-chain queries of ownership. /// Optional method for ERC-721. function tokensOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId) { uint256 count = 0; for (uint256 i = 1; i <= totalSupply(); i++) { if (kittyIndexToOwner[i] == _owner) { if (count == _index) { return i; } else { count++; } } } revert(); } } // File: contracts/KittyBreeding.sol /// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBreeding is KittyOwnership { /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId); /// @dev The AutoBirth event is fired when a cat becomes pregant via the breedWithAuto() /// function. This is used to notify the auto-birth daemon that this breeding action /// included a pre-payment of the gas required to call the giveBirth() function. event AutoBirth(uint256 matronId, uint256 cooldownEndTime); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by the auto-birth daemon, and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 1000000 * 1000000000; // (1M * 1 gwei) /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) public onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Kitty _kit) internal view returns (bool) { // In addition to checking the cooldownEndTime, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndTime <= now); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = kittyIndexToOwner[_matronId]; address sireOwner = kittyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _kitten A reference to the Kitty in storage which needs its timer started. function _triggerCooldown(Kitty storage _kitten) internal { // Compute the end of the cooldown time (based on current cooldownIndex) _kitten.cooldownEndTime = uint64(now + cooldowns[_kitten.cooldownIndex]); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_kitten.cooldownIndex < 13) { _kitten.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Kitties. /// @param _addr The address that will be able to sire with your Kitty. Set to /// address(0) to clear all siring approvals for this Kitty. /// @param _sireId A Kitty that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) public whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) public onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndTime <= now); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _kittyId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; return _isReadyToBreed(kit); } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Kitty struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Kitty struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Kitty storage _matron, uint256 _matronId, Kitty storage _sire, uint256 _sireId ) private view returns(bool) { // A Kitty can't breed with itself! if (_matronId == _sireId) { return false; } // Kitties can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Kitties can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two cats can breed together, including checks for /// ownership and siring approvals. Does NOT check that both cats are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) public view returns(bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) function breedWith(uint256 _matronId, uint256 _sireId) public whenNotPaused { // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Kitty on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Kitty storage matron = kitties[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Kitty storage sire = kitties[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, kitty gets pregnant! _breedWith(_matronId, _sireId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { // Grab a reference to the Kitties from storage. Kitty storage sire = kitties[_sireId]; Kitty storage matron = kitties[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Emit the pregnancy event. Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId); } /// @notice Works like breedWith(), but includes a pre-payment of the gas required to call /// the giveBirth() function when gestation is over. This will allow our autobirth daemon /// to call giveBirth() as soon as the gestation timer finishes. The required payment is given /// by autoBirthFee(). /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) public payable whenNotPaused { // Check for payment require(msg.value >= autoBirthFee); // Call through the normal breeding flow breedWith(_matronId, _sireId); // Emit an AutoBirth message so the autobirth daemon knows when and for what cat to call // giveBirth(). Kitty storage matron = kitties[_matronId]; AutoBirth(_matronId, matron.cooldownEndTime); } /// @notice Have a pregnant Kitty give birth! /// @param _matronId A Kitty ready to give birth. /// @return The Kitty ID of the new kitten. /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. function giveBirth(uint256 _matronId) public whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Kitty storage matron = kitties[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Kitty storage sire = kitties[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret, sooper-expensive, gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes); // Make the new kitten! address owner = kittyIndexToOwner[_matronId]; uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // return the new kitten's ID return kittenId; } } // File: contracts/KittyAuction.sol /// @title Handles creating auctions for sale and siring of kitties. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract KittyAuction is KittyBreeding { /// @dev The address of the ClockAuction contract that handles sales of Kitties. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAution subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) public onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) public onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a kitty up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); _approve(_kittyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. saleAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a kitty up for auction to be sire. /// Performs checks to ensure the kitty can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); _approve(_kittyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) public payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); uint256 currPrice = siringAuction.getCurrentPrice(_sireId); uint256 bidAmount = msg.value; bool doAutoBirth = false; if (bidAmount >= currPrice + autoBirthFee) { bidAmount -= autoBirthFee; doAutoBirth = true; } // Siring auction will throw if the bid fails. siringAuction.bid.value(bidAmount)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); if (doAutoBirth) { // Auto birth fee provided, trigger autobirth event Kitty storage matron = kitties[_matronId]; AutoBirth(_matronId, matron.cooldownEndTime); } } /// @dev Transfers the balance of the sale auction contract /// to the KittyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCOO { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } // File: contracts/KittyMinting.sol // Auction wrapper functions /// @title all functions related to creating kittens contract KittyMinting is KittyAuction { // Limits the number of cats the contract owner can ever create. uint256 public promoCreationLimit = 5000; uint256 public gen0CreationLimit = 50000; // Constants for gen0 auctions. uint256 public gen0StartingPrice = 10 trx; uint256 public gen0AuctionDuration = 1 days; // Counts the number of cats the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo kittens, up to a limit. Only callable by COO /// @param _genes the encoded genes of the kitten to be created, any value is accepted /// @param _owner the future owner of the created kittens. Default to contract COO function createPromoKitty(uint256 _genes, address _owner) public onlyCOO { if (_owner == address(0)) { _owner = cooAddress; } require(promoCreatedCount < promoCreationLimit); require(gen0CreatedCount < gen0CreationLimit); promoCreatedCount++; gen0CreatedCount++; _createKitty(0, 0, 0, _genes, _owner); } /// @dev Creates a new gen0 kitty with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes) public onlyCOO { require(gen0CreatedCount < gen0CreationLimit); uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); _approve(kittyId, saleAuction); saleAuction.createAuction( kittyId, _computeNextGen0Price(), 0, gen0AuctionDuration, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } } // File: contracts/KittyCore.sol // // Auction wrapper functions /// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. contract KittyCore is KittyMinting { // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - KittyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - KittyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - KittyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - KittyBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. // We can make up to 5000 "promo" cats that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoKitties smart contract instance. function KittyCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical kitten 0 - so we don't have generation-0 parent issues _createKitty(0, 0, 0, uint256(-1), address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getKitty(uint256 _id) public view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Kitty storage kit = kitties[_id]; // if this variable is 0 then it's not gestating isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndTime <= now); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndTime); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } }
The Pregnant event is fired when two cats successfully breed and the pregnancy timer begins for the matron. The AutoBirth event is fired when a cat becomes pregant via the breedWithAuto() function. This is used to notify the auto-birth daemon that this breeding action included a pre-payment of the gas required to call the giveBirth() function. The minimum payment required to use breedWithAuto(). This fee goes towards the gas cost paid by the auto-birth daemon, and can be dynamically updated by the COO role as the gas price changes. The address of the sibling contract that is used to implement the sooper-sekret genetic combination algorithm. Update the address of the genetic contract, can only be called by the CEO. _address An address of a GeneScience contract instance to be used from this point forward. NOTE: verify that a contract is what we expect - https:github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.solL117 Set the new contract address
function setGeneScienceAddress(address _address) public onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); geneScience = candidateContract; }
6,444,573
./partial_match/4/0x03824267Bc2f86502f0fD5148C9293dC82F6BdCC/sources/OptionMarket.sol
Calculates the LMSR cost function C(q_1, ..., q_n) = b log(exp(q_1 / b) + ... + exp(q_n / b)) where q_i = total supply of ith spread b = liquidity parameter An equivalent expression for C is used to avoid overflow when calculating exponentials C(q_1, ..., q_n) = m + b log(exp((q_1 - m) / b) + ... + exp((q_n - m) / b)) where m = max(q_1, ..., q_n)/ max(q) - q_i (max(q) - q_i) / b exp((q_i - max(q)) / b)
function calcCumulativeCost(uint256[] memory quantities) public view returns (uint256) { require(quantities.length == numStrikes + 1, "Lengths do not match"); if (b == 0) { return 0; } uint256 maxQuantity = quantities[0]; for (uint256 i = 1; i < quantities.length; i++) { maxQuantity = Math.max(maxQuantity, quantities[i]); } int128 sumExp; for (uint256 i = 0; i < quantities.length; i++) { uint256 diff = maxQuantity.sub(quantities[i]); int128 div = ABDKMath64x64.divu(diff, b); int128 exp = ABDKMath64x64.exp(ABDKMath64x64.neg(div)); sumExp = ABDKMath64x64.add(sumExp, exp); } }
8,544,280
./full_match/1/0xE39994e70D370Daf6AA46969abD69B6801A675e4/sources/localhost/contracts/UniswapOTC.sol
Get token balance/
function tokenBalance() public view returns (uint256) { return token.balanceOf(address(this)); }
3,196,921
./full_match/1/0x9f044E02483d50294fb702b512553B6f2b30D30F/sources/contracts/bets.sol
settle and claim for previous indexprepare new condition
function execute(address oracle, uint256 interval) external onlyOperator { require(oracle != address(0), "ERR_INVALID_CONDITION_INDEX"); uint256 index = autoGeneratedMarkets[oracle][interval]; require(index != 0, "ERR_INITIALIZE_MARKET"); claimFor(msg.sender, index); int256 triggerPrice = getPrice(oracle); uint256 newIndex = prepareCondition(oracle, interval, triggerPrice, false); autoGeneratedMarkets[oracle][interval] = newIndex; emit NewMarketGenerated(newIndex, oracle); }
8,292,029
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./SafeERC20.sol"; import "./Wines.sol"; // Have fun reading it. Hopefully it's bug-free. God bless. contract WinesMaster is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; //LP TOKEN balance uint256 rewardDebt; } struct PoolInfo { IERC20 lpToken; uint256 weightPoint; uint256 share; uint256 lastRewardBlock; } struct PioneerInfo { uint256 poolId; uint256 endBlock; uint256 totalReward; uint256 blockReward; uint256 startBlock; uint256 rewardBalance; uint256 startRewardDebt; uint256 endRewardDebt; } // The GIFT TOKEN! WinesToken public giftToken; // the Owner address address public fundPool; // block interval for miner difficult update uint256 public difficultyChangeBlock; // the reward of each block. uint256 public minerBlockReward; uint256 public currentDifficulty; // the reward for developer rato uint256 public constant DEVELOPER_RATO = 10; uint256 public constant INTERVAL = 1e12; // the migrator token IMigratorToken public migrator; // Deposit pool array PoolInfo[] public poolInfoList; // userinfo map mapping (uint256 => mapping (address => UserInfo)) public userInfoMap; // pioneerInfo map mapping (uint256 => PioneerInfo) public pioneerInfoMap; // total alloc point uint256 public totalWeightPoint = 0; // miner start block uint256 public startBlock; // miner block num for test // uint256 public testBlockNum; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor(WinesToken _gift, uint256 _startBlock, uint256 _minerBlockReward, address _fundPoolAddress) public { giftToken = _gift; fundPool = _fundPoolAddress; startBlock = _startBlock; minerBlockReward = _minerBlockReward; } // constructor(WinesToken _gift) public { // giftToken = _gift; // fundPool = address(msg.sender); // startBlock = block.number; // testBlockNum = block.number; // minerBlockReward = 70; // } // ** The function below is for user operation // deposit lp token function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfoList[_pid]; UserInfo storage user = userInfoMap[_pid][msg.sender]; pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); updatePool(_pid); uint256 pending = pendingReward(_pid, msg.sender); if(pending > 0) { userRewardSender(pending, _pid, msg.sender); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.share).div(INTERVAL); emit Deposit(msg.sender, _pid, _amount); } // update share of all pools function updateAllPools() public { uint256 length = poolInfoList.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // withdraw lpToken form Deposit pool function withdraw(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfoList[_pid]; UserInfo storage user = userInfoMap[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: amount not enough"); updatePool(_pid); uint256 pending = pendingReward(_pid, msg.sender); if(pending > 0) { userRewardSender(pending, _pid, msg.sender); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.share).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfoList[_pid]; UserInfo storage user = userInfoMap[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // withdraw reward form Deposit pool function withdrawReward(uint256 _pid) external { PoolInfo storage pool = poolInfoList[_pid]; UserInfo storage user = userInfoMap[_pid][msg.sender]; updatePool(_pid); uint256 pending = pendingReward(_pid, msg.sender); require(pending >= 0, "withdrawReward: reward pool empty"); userRewardSender(pending, _pid, msg.sender); user.rewardDebt = user.amount.mul(pool.share).div(1e12); } // ** The function below is for display parameters // the length of deposit pool function poolLength() external view returns (uint256) { return poolInfoList.length; } // show the pending reward function pendingReward(uint256 _pid, address _user) public view returns (uint256) { if(block.number < startBlock) return 0; PoolInfo storage pool = poolInfoList[_pid]; UserInfo storage user = userInfoMap[_pid][_user]; uint256 blockInterval = block.number.sub(pool.lastRewardBlock); // if (user.depositBlock == 0 || user.depositBlock > block.number) { // uint256 blockInterval = testBlockNum.sub(pool.lastRewardBlock); if(pool.lpToken.balanceOf(address(this)) == 0) { return 0; } if (pool.lastRewardBlock == 0 || pool.lastRewardBlock > block.number) { // if (pool.lastRewardBlock == 0 || pool.lastRewardBlock > testBlockNum) { return 0; } uint256 share = pool.share.add(blockInterval.mul(minerBlockReward).mul(INTERVAL).mul(pool.weightPoint).div(totalWeightPoint).div(pool.lpToken.balanceOf(address(this)))); uint256 pendingAmount = user.amount.mul(share).div(INTERVAL).sub(user.rewardDebt); pendingAmount = giftToken.balanceOf(address(this)) > pendingAmount ? pendingAmount : giftToken.balanceOf(address(this)); pendingAmount = pendingAmount.add(getPioneerReward(_pid, _user)); return pendingAmount; } // ** The function below is for private function // send user reward function userRewardSender(uint256 rewardAmount, uint256 _pid, address _user) private { uint256 lpSupply = giftToken.balanceOf(address(this)); if (lpSupply == 0) { return; } if(rewardAmount > 0) { giftToken.transfer(fundPool, rewardAmount.mul(9).div(10).div(10)); giftToken.transfer(msg.sender, rewardAmount.mul(9).div(10)); giftToken.burn(rewardAmount.div(10).div(10)); giftToken.burn(rewardAmount.div(10)); uint256 pioneerAmount = getPioneerReward(_pid, _user); if(pioneerAmount > 0) { pioneerInfoMap[_pid].rewardBalance = pioneerInfoMap[_pid].rewardBalance.sub(pioneerAmount); } } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfoList[_pid]; if (block.number <= pool.lastRewardBlock) { // if (testBlockNum <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; // pool.lastRewardBlock = testBlockNum; return; } uint256 winessReward = (block.number.sub(pool.lastRewardBlock)).mul(minerBlockReward).mul(pool.weightPoint).div(totalWeightPoint); // uint256 winessReward = (testBlockNum.sub(pool.lastRewardBlock)).mul(minerBlockReward).mul(pool.weightPoint).div(totalWeightPoint); pool.share = pool.share.add(winessReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; // pool.lastRewardBlock = testBlockNum; if(pioneerInfoMap[_pid].endBlock > block.number && block.number > pioneerInfoMap[_pid].startBlock) { // if(pioneerInfoMap[_pid].endBlock > testBlockNum && testBlockNum > pioneerInfoMap[_pid].startBlock) { pioneerInfoMap[_pid].endRewardDebt = pool.share; } } //get pioneer reward amount function getPioneerReward(uint256 _pid, address _user) public view returns (uint256) { PioneerInfo storage pioneer = pioneerInfoMap[_pid]; if(pioneer.startBlock == 0) { return 0; } PoolInfo storage pool = poolInfoList[_pid]; UserInfo storage user = userInfoMap[_pid][_user]; uint256 startShare = user.rewardDebt > pioneer.startRewardDebt ? user.rewardDebt : pioneer.startRewardDebt; uint256 endShare; if (pool.lastRewardBlock > pioneer.endBlock) { endShare = pioneer.endRewardDebt; } else { // uint256 blockInterval = (pioneer.endBlock > testBlockNum ? testBlockNum : pioneer.endBlock).sub(pool.lastRewardBlock); uint256 blockInterval = (pioneer.endBlock > block.number ? block.number : pioneer.endBlock).sub(pool.lastRewardBlock); endShare = pool.share.add(blockInterval.mul(minerBlockReward).mul(INTERVAL).mul(pool.weightPoint).div(totalWeightPoint).div(pool.lpToken.balanceOf(address(this)))); } if(startShare > endShare) return 0; uint256 pioneerReward = user.amount.mul(endShare.sub(startShare)).mul(pioneer.blockReward).div(minerBlockReward).div(INTERVAL); return pioneerReward > pioneer.rewardBalance ? pioneer.rewardBalance : pioneerReward; } // gift token transfer function giftTokenTransfer(address _to, uint256 _amount) internal { uint256 balance = giftToken.balanceOf(address(this)); if (_amount > balance) { giftToken.transfer(_to, balance); } else { giftToken.transfer(_to, _amount); } } // ** The function below is for contract developer // add the new Deposit pool function add(uint256 _weightPoint, IERC20 _lpToken) public onlyOwner { totalWeightPoint = totalWeightPoint.add(_weightPoint); updateAllPools(); poolInfoList.push(PoolInfo({ lpToken: _lpToken, weightPoint: _weightPoint, share: 0, lastRewardBlock: block.number // lastRewardBlock: testBlockNum })); } // update the miner difficulty function updateMinerDifficulty() public onlyOwner{ require(currentDifficulty < 6,"updateMinerDifficulty: max Difficulty"); currentDifficulty = currentDifficulty.add(1); minerBlockReward = minerBlockReward.div(2); } // set the pioneer reward info function setPioneer(uint256 _pioneerTotalReward, uint256 _pioneerBlockReward, uint256 _pioneerEndBlock, uint256 _pioneerStartBlock, uint256 _pioneerPoolId) external onlyOwner { require(_pioneerTotalReward >= 0, "setPioneer: total reward value error"); require(_pioneerBlockReward > 0, "setPioneer: block reward value error"); require(_pioneerEndBlock > 0, "setPioneer: block interval value error"); require(_pioneerPoolId < poolInfoList.length, "setPioneer: out off index error"); PioneerInfo storage pioneerInfo = pioneerInfoMap[_pioneerPoolId]; pioneerInfo.poolId = _pioneerPoolId; pioneerInfo.totalReward = _pioneerTotalReward; pioneerInfo.blockReward = _pioneerBlockReward; pioneerInfo.endBlock = _pioneerEndBlock; pioneerInfo.startBlock = _pioneerStartBlock; pioneerInfo.rewardBalance = _pioneerTotalReward; pioneerInfo.startRewardDebt = poolInfoList[_pioneerPoolId].share; pioneerInfo.endRewardDebt = poolInfoList[_pioneerPoolId].share; } // change the fund pool address function changeFundPoolAddress(address _fundPool) public { require(msg.sender == fundPool, "dev: Insufficient permissions?"); fundPool = _fundPool; } // update weightPoint of deposit pool function set(uint256 _pid, uint256 _weightPoint) public onlyOwner { updateAllPools(); totalWeightPoint = totalWeightPoint.sub(poolInfoList[_pid].weightPoint).add(_weightPoint); poolInfoList[_pid].weightPoint = _weightPoint; } // set the migrator contract address. function setMigrator(IMigratorToken _migrator) public onlyOwner { migrator = _migrator; } // migrate the lp token to a new lp token contract function migrate(uint256 _pid) public onlyOwner { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfoList[_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; } } interface IMigratorToken { function migrate(IERC20 token) external returns (IERC20); }
gift token transfer
function giftTokenTransfer(address _to, uint256 _amount) internal { uint256 balance = giftToken.balanceOf(address(this)); if (_amount > balance) { giftToken.transfer(_to, balance); giftToken.transfer(_to, _amount); } }
12,763,259
// SPDX-License-Identifier: MIT // /$$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$$ /$$$$$$$$ /$$ /$$ //| $$__ $$|_ $$_/| $$ /$$/ /$$__ $$ | $$_____/ /$$__ $$ /$$__ $$ /$$__ $$| $$ /$$//$$__ $$|__ $$__/| $$_____/| $$$ /$$$ //| $$ \ $$ | $$ | $$ /$$/ | $$ \ $$ | $$ | $$ \__/| $$ \ $$| $$ \__/ \ $$ /$$/| $$ \__/ | $$ | $$ | $$$$ /$$$$ //| $$$$$$$/ | $$ | $$$$$/ | $$$$$$$$ | $$$$$ | $$ | $$ | $$| $$$$$$ \ $$$$/ | $$$$$$ | $$ | $$$$$ | $$ $$/$$ $$ //| $$____/ | $$ | $$ $$ | $$__ $$ | $$__/ | $$ | $$ | $$ \____ $$ \ $$/ \____ $$ | $$ | $$__/ | $$ $$$| $$ //| $$ | $$ | $$\ $$ | $$ | $$ | $$ | $$ $$| $$ | $$ /$$ \ $$ | $$ /$$ \ $$ | $$ | $$ | $$\ $ | $$ //| $$ /$$$$$$| $$ \ $$| $$ | $$ | $$$$$$$$| $$$$$$/| $$$$$$/| $$$$$$/ | $$ | $$$$$$/ | $$ | $$$$$$$$| $$ \/ | $$ //|__/ |______/|__/ \__/|__/ |__/ |________/ \______/ \______/ \______/ |__/ \______/ |__/ |________/|__/ |__/ // website: https://pikacrypto.com pragma solidity 0.8.4; interface IThunder { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function burn(uint256 value) external; } pragma solidity 0.8.4; contract Owned { address public owner; address public proposedOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() virtual { require(msg.sender == owner); _; } /** * @dev propeses a new owner * Can only be called by the current owner. */ function proposeOwner(address payable _newOwner) external onlyOwner { proposedOwner = _newOwner; } /** * @dev claims ownership of the contract * Can only be called by the new proposed owner. */ function claimOwnership() external { require(msg.sender == proposedOwner); emit OwnershipTransferred(owner, proposedOwner); owner = proposedOwner; } } pragma solidity 0.8.4; contract ThunderStaking is Owned { address public teamWallet; uint256 public totalAmountStaked = 0; mapping(address => uint256) public balances; mapping(address => uint256) public claimPeriods; IThunder public thunder; uint256 public periodNonce = 0; uint256 public periodFinish; uint256 public minPeriodDuration = 14 days; uint256 public rewardPerToken = 0; uint256 public maxInitializationReward; event Staked(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event RewardClaimed(address indexed user, uint256 amount); event StakingPeriodStarted(uint256 totalRewardPool, uint256 periodFinish); event MinPeriodDurationUpdated(uint256 oldDuration, uint256 newDuration); event MaxInitializationRewardUpdated(uint256 oldValue, uint256 newValue); constructor(address _token, address _teamWallet) { thunder = IThunder(_token); teamWallet = _teamWallet; maxInitializationReward = 100000 ether; periodFinish = block.timestamp + 3 days; } /** * @notice allows a user to stake tokens * @dev requires to claim pending rewards before being able to stake more tokens * @param _amount of tokens to stake */ function stake(uint256 _amount) public { uint256 balance = balances[msg.sender]; if (balance > 0) { require(claimPeriods[msg.sender] == periodNonce, "Claim your reward before staking more tokens"); } thunder.transferFrom(msg.sender, address(this), _amount); uint256 burnedAmount = (_amount * 6) / 100; thunder.burn(burnedAmount); uint256 teamWalletAmount = (_amount * 1) / 100; thunder.transfer(teamWallet, teamWalletAmount); uint256 userBalance = _amount - burnedAmount - teamWalletAmount; balances[msg.sender] += userBalance; claimPeriods[msg.sender] = periodNonce; totalAmountStaked += userBalance; emit Staked(msg.sender, userBalance); } /** * @notice allows a user to withdraw staked tokens * @dev unclaimed tokens cannot be claimed after withdrawal * @dev unstakes all tokens */ function withdraw() public { uint256 balance = balances[msg.sender]; balances[msg.sender] = 0; totalAmountStaked -= balance; thunder.transfer(msg.sender, balance); emit Withdraw(msg.sender, balance); } /** * @notice claims a reward for the staked tokens * @dev can only claim once per staking period */ function claimReward() public { uint256 balance = balances[msg.sender]; require(balance > 0, "No tokens staked"); require(claimPeriods[msg.sender] < periodNonce, "Wait for this period to finish before claiming your reward"); claimPeriods[msg.sender] = periodNonce; uint256 reward = (balance * rewardPerToken) / 1 ether; thunder.transfer(msg.sender, reward); emit RewardClaimed(msg.sender, reward); } /** * @notice returns claimable reward for a user * @param _user to check */ function claimableReward(address _user) public view returns (uint256) { if (claimPeriods[_user] == periodNonce) { return 0; } return (balances[_user] * rewardPerToken) / 1 ether; } /** * @notice initializes new staking claim period * @dev requires previous staking period to be over * @dev only callable by anyone, msg.sender receives a portion of the staking pool as a reward */ function initNewRewardPeriod() external { require(block.timestamp >= periodFinish, "Wait for claim period to finish"); require(totalAmountStaked > 0, "No tokens staked in contract"); uint256 rewardPool = thunder.balanceOf(address(this)) - totalAmountStaked; uint256 initializationReward = rewardPool / 1000; if (initializationReward > maxInitializationReward) { initializationReward = maxInitializationReward; } rewardPool -= initializationReward; thunder.transfer(msg.sender, initializationReward); rewardPerToken = (rewardPool * 1 ether) / totalAmountStaked; periodNonce++; periodFinish = block.timestamp + minPeriodDuration; emit StakingPeriodStarted(rewardPool, periodFinish); } /** * @notice sets a new minimum duration for each staking claim period * @dev only callable by owner * @param _days amount of days the new staking claim period should at least last */ function setMinDuration(uint256 _days) external onlyOwner { emit MinPeriodDurationUpdated(minPeriodDuration / 1 days, _days); minPeriodDuration = _days * 1 days; } /** * @notice sets maximum initialization reward * @dev only callable by owner * @param _newMaxReward new maximum reward paid out by initNewRewardPeriod function */ function setMaxInitializationReward(uint256 _newMaxReward) external onlyOwner { emit MaxInitializationRewardUpdated(maxInitializationReward, _newMaxReward); maxInitializationReward = _newMaxReward; } }
returns claimable reward for a user _user to check/
function claimableReward(address _user) public view returns (uint256) { if (claimPeriods[_user] == periodNonce) { return 0; } return (balances[_user] * rewardPerToken) / 1 ether; }
13,859,116
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./extensions/ERC20Internal.sol"; import "../../Interfaces/IERC20Extended.sol"; import "../WithSuperOperators.sol"; abstract contract ERC20BaseToken is WithSuperOperators, IERC20, IERC20Extended, ERC20Internal { bytes32 internal immutable _name; // works only for string that can fit into 32 bytes bytes32 internal immutable _symbol; // works only for string that can fit into 32 bytes address internal immutable _operator; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory tokenName, string memory tokenSymbol, address admin, address operator ) { require(bytes(tokenName).length > 0, "INVALID_NAME_REQUIRED"); require(bytes(tokenName).length <= 32, "INVALID_NAME_TOO_LONG"); _name = _firstBytes32(bytes(tokenName)); require(bytes(tokenSymbol).length > 0, "INVALID_SYMBOL_REQUIRED"); require(bytes(tokenSymbol).length <= 32, "INVALID_SYMBOL_TOO_LONG"); _symbol = _firstBytes32(bytes(tokenSymbol)); _admin = admin; _operator = operator; } /// @notice Transfer `amount` tokens to `to`. /// @param to The recipient address of the tokens being transfered. /// @param amount The number of tokens being transfered. /// @return success Whether or not the transfer succeeded. function transfer(address to, uint256 amount) external override returns (bool success) { _transfer(msg.sender, to, amount); return true; } /// @notice Transfer `amount` tokens from `from` to `to`. /// @param from The origin address of the tokens being transferred. /// @param to The recipient address of the tokensbeing transfered. /// @param amount The number of tokens transfered. /// @return success Whether or not the transfer succeeded. function transferFrom( address from, address to, uint256 amount ) external override returns (bool success) { if (msg.sender != from && !_superOperators[msg.sender] && msg.sender != _operator) { uint256 currentAllowance = _allowances[from][msg.sender]; if (currentAllowance != ~uint256(0)) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) require(currentAllowance >= amount, "NOT_AUTHORIZED_ALLOWANCE"); _allowances[from][msg.sender] = currentAllowance - amount; } } _transfer(from, to, amount); return true; } /// @notice Burn `amount` tokens. /// @param amount The number of tokens to burn. function burn(uint256 amount) external override { _burn(msg.sender, amount); } /// @notice Burn `amount` tokens from `owner`. /// @param from The address whose token to burn. /// @param amount The number of tokens to burn. function burnFor(address from, uint256 amount) external override { if (msg.sender != from && !_superOperators[msg.sender] && msg.sender != _operator) { uint256 currentAllowance = _allowances[from][msg.sender]; if (currentAllowance != ~uint256(0)) { require(currentAllowance >= amount, "NOT_AUTHORIZED_ALLOWANCE"); _allowances[from][msg.sender] = currentAllowance - amount; } } _burn(from, amount); } /// @notice Approve `spender` to transfer `amount` tokens. /// @param spender The address to be given rights to transfer. /// @param amount The number of tokens allowed. /// @return success Whether or not the call succeeded. function approve(address spender, uint256 amount) external override returns (bool success) { _approveFor(msg.sender, spender, amount); return true; } /// @notice Get the name of the token collection. /// @return The name of the token collection. function name() external view returns (string memory) { return string(abi.encodePacked(_name)); } /// @notice Get the symbol for the token collection. /// @return The symbol of the token collection. function symbol() external view returns (string memory) { return string(abi.encodePacked(_symbol)); } /// @notice Get the total number of tokens in existence. /// @return The total number of tokens in existence. function totalSupply() external view override returns (uint256) { return _totalSupply; } /// @notice Get the balance of `owner`. /// @param owner The address to query the balance of. /// @return The amount owned by `owner`. function balanceOf(address owner) external view override returns (uint256) { return _balances[owner]; } /// @notice Get the allowance of `spender` for `owner`'s tokens. /// @param owner The address whose token is allowed. /// @param spender The address allowed to transfer. /// @return remaining The amount of token `spender` is allowed to transfer on behalf of `owner`. function allowance(address owner, address spender) external view override returns (uint256 remaining) { return _allowances[owner][spender]; } /// @notice Get the number of decimals for the token collection. /// @return The number of decimals. function decimals() external pure virtual returns (uint8) { return uint8(18); } /// @notice Approve `spender` to transfer `amount` tokens from `owner`. /// @param owner The address whose token is allowed. /// @param spender The address to be given rights to transfer. /// @param amount The number of tokens allowed. /// @return success Whether or not the call succeeded. function approveFor( address owner, address spender, uint256 amount ) public override returns (bool success) { require(msg.sender == owner || _superOperators[msg.sender] || msg.sender == _operator, "NOT_AUTHORIZED"); // TODO metatx _approveFor(owner, spender, amount); return true; } /// @notice Increase the allowance for the spender if needed /// @param owner The address of the owner of the tokens /// @param spender The address wanting to spend tokens /// @param amountNeeded The amount requested to spend /// @return success Whether or not the call succeeded. function addAllowanceIfNeeded( address owner, address spender, uint256 amountNeeded ) public returns (bool success) { require(msg.sender == owner || _superOperators[msg.sender] || msg.sender == _operator, "INVALID_SENDER"); _addAllowanceIfNeeded(owner, spender, amountNeeded); return true; } /// @notice Get the first 32 bytes of input `src`. /// @param src The input data /// @return output The first 32 bytes of `src`. function _firstBytes32(bytes memory src) public pure returns (bytes32 output) { // solhint-disable-next-line no-inline-assembly assembly { output := mload(add(src, 32)) } } /// @dev See addAllowanceIfNeeded. function _addAllowanceIfNeeded( address owner, address spender, uint256 amountNeeded ) internal override { if (amountNeeded > 0 && !isSuperOperator(spender) && spender != _operator) { uint256 currentAllowance = _allowances[owner][spender]; if (currentAllowance < amountNeeded) { _approveFor(owner, spender, amountNeeded); } } } /// @dev See approveFor. function _approveFor( address owner, address spender, uint256 amount ) internal override { require(owner != address(0) && spender != address(0), "INVALID_OWNER_||_SPENDER"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /// @dev See transfer. function _transfer( address from, address to, uint256 amount ) internal override { require(to != address(0), "NOT_TO_ZEROADDRESS"); require(to != address(this), "NOT_TO_THIS"); uint256 currentBalance = _balances[from]; require(currentBalance >= amount, "INSUFFICIENT_FUNDS"); _balances[from] = currentBalance - amount; _balances[to] += amount; emit Transfer(from, to, amount); } /// @dev Mint tokens for a recipient. /// @param to The recipient address. /// @param amount The number of token to mint. function _mint(address to, uint256 amount) internal { require(to != address(0), "NOT_TO_ZEROADDRESS"); require(amount > 0, "MINT_O_TOKENS"); uint256 currentTotalSupply = _totalSupply; uint256 newTotalSupply = currentTotalSupply + amount; require(newTotalSupply > currentTotalSupply, "OVERFLOW"); _totalSupply = newTotalSupply; _balances[to] += amount; emit Transfer(address(0), to, amount); } /// @dev Burn tokens from an address. /// @param from The address whose tokens to burn. /// @param amount The number of token to burn. function _burn(address from, uint256 amount) internal { require(amount > 0, "BURN_O_TOKENS"); if (msg.sender != from && !_superOperators[msg.sender] && msg.sender != _operator) { uint256 currentAllowance = _allowances[from][msg.sender]; require(currentAllowance >= amount, "INSUFFICIENT_ALLOWANCE"); if (currentAllowance != ~uint256(0)) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) _allowances[from][msg.sender] = currentAllowance - amount; } } uint256 currentBalance = _balances[from]; require(currentBalance >= amount, "INSUFFICIENT_FUNDS"); _balances[from] = currentBalance - amount; _totalSupply -= amount; emit Transfer(from, address(0), amount); } }
Get the balance of `owner`. owner The address to query the balance of. return The amount owned by `owner`.
function balanceOf(address owner) external view override returns (uint256) { return _balances[owner]; }
1,808,143
pragma solidity ^0.4.12; /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function safeSub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal constant 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; } } /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMath { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; /** * * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address _spender, uint _addedValue) onlyPayloadSize(2 * 32) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; allowed[msg.sender][_spender] = safeAdd(oldValue, _addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address _spender, uint _subtractedValue) onlyPayloadSize(2 * 32) returns (bool success) { uint oldVal = allowed[msg.sender][_spender]; if (_subtractedValue > oldVal) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldVal, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is StandardToken { address public constant BURN_ADDRESS = 0; /** How many tokens we burned */ event Burned(address burner, uint burnedAmount); /** * Burn extra tokens from a balance. * */ function burn(uint burnAmount) { address burner = msg.sender; balances[burner] = safeSub(balances[burner], burnAmount); totalSupply = safeSub(totalSupply, burnAmount); Burned(burner, burnAmount); } } /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don&#39;t have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { // Called in a bad state throw; } // Validate input value. if (value == 0) throw; balances[msg.sender] = safeSub(balances[msg.sender], value); // Take tokens out from circulation totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading throw; } if (agent == 0x0) throw; // Only a master can designate the next agent if (msg.sender != upgradeMaster) throw; // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) throw; upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) throw; // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) throw; UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns(bool) { return true; } } contract Lescoin is BurnableToken, UpgradeableToken { string public name; string public symbol; uint public decimals; function Lescoin(address _owner, address _init) UpgradeableToken(_owner) { name = "Lescoin"; symbol = "LSC"; totalSupply = 200000000000000; decimals = 8; // Allocate initial balance to the init account balances[_init] = totalSupply; } } contract LescoinPreSale { address public beneficiary; address public coldWallet; uint public ethPrice; uint public bonus; uint public amountRaised; Lescoin public tokenReward; uint constant public price = 50; uint constant public minSaleAmount = 10000; function LescoinPreSale( address _beneficiary, address _coldWallet, uint _ethPrice, uint _bonus, Lescoin _addressOfToken ) { beneficiary = _beneficiary; coldWallet = _coldWallet; ethPrice = _ethPrice; bonus = _bonus; tokenReward = Lescoin(_addressOfToken); } function () payable { uint amount = msg.value; uint tokenAmount = amount * ethPrice / price / 1000000000000; if (tokenAmount < minSaleAmount) throw; amountRaised += amount; tokenReward.transfer(msg.sender, tokenAmount * (100 + bonus) / 100); } function WithdrawETH(uint _amount) { if (beneficiary != msg.sender) throw; coldWallet.transfer(_amount); } function WithdrawTokens(uint _amount) { if (beneficiary != msg.sender) throw; tokenReward.transfer(coldWallet, _amount); } function TransferTokens(address _to, uint _amount) { if (beneficiary != msg.sender) throw; tokenReward.transfer(_to, _amount); } function ChangeEthPrice(uint _ethPrice) { if (beneficiary != msg.sender) throw; ethPrice = _ethPrice; } function ChangeBonus(uint _bonus) { if (beneficiary != msg.sender) throw; bonus = _bonus; } }
Allocate initial balance to the init account
function Lescoin(address _owner, address _init) UpgradeableToken(_owner) { name = "Lescoin"; symbol = "LSC"; totalSupply = 200000000000000; decimals = 8; balances[_init] = totalSupply; }
2,391,835
pragma solidity >0.5.4; import "@daostack/arc/contracts/controller/Avatar.sol"; /* @title Abstract contract responsible for ensuring a scheme is only usable within a set period */ contract ActivePeriod { uint256 public periodStart; uint256 public periodEnd; bool public isActive; Avatar avatar; event SchemeStarted(address indexed by, uint256 time); event SchemeEnded(address indexed by, uint256 time); /* @dev modifier that requires scheme to be active */ modifier requireActive() { require(isActive, "is not active"); _; } /* @dev modifier that requires scheme to not be active */ modifier requireNotActive() { require(!isActive, "cannot start twice"); _; } /* @dev modifier that requires current time to be after period start and before period end */ modifier requireInPeriod() { require(now >= periodStart && now < periodEnd, "not in period"); _; } /* @dev modifier that requires current time to be after period end */ modifier requirePeriodEnd() { require(now >= periodEnd, "period has not ended"); _; } /* @dev Constructor. requires end period to be larger than start period * Sets local period parameters and sets isActive to false * @param _periodStart The time from when the contract can be started * @param _periodEnd The time from when the contract can be ended * @param _avatar DAO avatar */ constructor( uint256 _periodStart, uint256 _periodEnd, Avatar _avatar ) public { require(_periodStart < _periodEnd, "start cannot be after nor equal to end"); periodStart = _periodStart; periodEnd = _periodEnd; avatar = _avatar; isActive = false; } /* @dev Function to start scheme. Must be inactive and within period. * Sets isActive to true and emits event with address that started and * current time. */ function start() public requireInPeriod requireNotActive { isActive = true; emit SchemeStarted(msg.sender, now); } /* @dev Function to end scheme. Must be after assigned period end. * Calls internal function internalEnd, passing along the avatar * @param _avatar the avatar of the dao */ function end() public requirePeriodEnd { return internalEnd(avatar); } /* @dev internal end function. Must be active to run. * Sets contract to inactive, emits an event with caller and * current time, and self-destructs the contract, transferring any * eth in the contract to the avatar address * @param _avatar the avatar of the dao */ function internalEnd(Avatar _avatar) internal requireActive { isActive = false; emit SchemeEnded(msg.sender, now); selfdestruct(address(_avatar)); } }
Function to end scheme. Must be after assigned period end. Calls internal function internalEnd, passing along the avatar _avatar the avatar of the dao/
function end() public requirePeriodEnd { return internalEnd(avatar); }
1,776,521
./partial_match/97/0xcB8796fdFd8043Da86b2DD567d6828318817E1d9/sources/CLIQ.sol
function to performs staking for user tokens for a specific period of time
function stakeToken(uint256 tokens, uint256 time) public tokenStakeCheck(tokens, time) returns(bool){ _stakingCount = _stakingCount +1 ; _time = now + (time * 1 days); _totalDays[_stakingCount] = time; _stakingAddress[_stakingCount] = msg.sender; _stakingEndTime[_stakingCount] = _time; _stakingStartTime[_stakingCount] = now; _usersTokens[_stakingCount] = tokens; _TokenTransactionstatus[_stakingCount] = false; _transfer(msg.sender, _tokenStakePoolAddress, tokens); return true; }
11,368,318
/** β–“β–“β–Œ β–“β–“ ▐▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–„ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–„β–„β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▄▄▄▄ β–“β–“β–“β–“β–“β–“β–„β–„β–„β–„ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–€ β–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–€β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓▀▀▀▀ β–“β–“β–“β–“β–“β–“β–€β–€β–€β–€ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ β–“β–“β–“β–“β–“β–“ β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ Trust math, not hardware. */ pragma solidity 0.5.17; import "@keep-network/keep-core/contracts/KeepToken.sol"; import "@keep-network/keep-core/contracts/TokenStaking.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/cryptography/MerkleProof.sol"; /// @title ECDSA Rewards distributor /// @notice This contract can be used by stakers to claim their rewards for /// participation in the keep network for operating ECDSA nodes. /// @dev This contract is based on the Uniswap's Merkle Distributor /// https://github.com/Uniswap/merkle-distributor with some modifications: /// - added a map of merkle root keys. Whenever a new merkle root is put in the /// map, we assign 'true' value to this key /// - added 'allocate()' function that will be called each time to allocate /// new KEEP rewards for a given merkle root. Merkle root is going to be generated /// regulary (ex. every week) and it is also means that an interval for that /// merkle root has passed /// - changed code accordingly to process claimed rewards using a map of merkle /// roots contract ECDSARewardsDistributor is Ownable { using SafeERC20 for KeepToken; KeepToken public token; TokenStaking public tokenStaking; // This event is triggered whenever a call to #claim succeeds. event RewardsClaimed( bytes32 indexed merkleRoot, uint256 indexed index, address indexed operator, address beneficiary, uint256 amount ); // This event is triggered whenever rewards are allocated. event RewardsAllocated(bytes32 merkleRoot, uint256 amount); // Map of merkle roots indicating whether a given interval was allocated with // KEEP token rewards. For each interval there is always created a new merkle // tree including a root, rewarded operators along with their amounts and proofs. mapping(bytes32 => bool) private merkleRoots; // Bytes32 key is a merkle root and the value is a packed array of booleans. mapping(bytes32 => mapping(uint256 => uint256)) private claimedBitMap; constructor(address _token, address _tokenStaking) public { token = KeepToken(_token); tokenStaking = TokenStaking(_tokenStaking); } /// Claim KEEP rewards for a given merkle root (interval) and the given operator /// address. Rewards will be sent to a beneficiary assigned to the operator. /// @param merkleRoot Merkle root for a given interval. /// @param index Index of the operator in the merkle tree. /// @param operator Operator address that reward will be claimed. /// @param amount The amount of KEEP reward to be claimed. /// @param merkleProof Array of merkle proofs. function claim( bytes32 merkleRoot, uint256 index, address operator, uint256 amount, bytes32[] calldata merkleProof ) external { require( merkleRoots[merkleRoot], "Rewards must be allocated for a given merkle root" ); require(!isClaimed(merkleRoot, index), "Reward already claimed"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, operator, amount)); require( MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof" ); // Mark it claimed and send the token. _setClaimed(merkleRoot, index); address beneficiary = tokenStaking.beneficiaryOf(operator); require(IERC20(token).transfer(beneficiary, amount), "Transfer failed"); emit RewardsClaimed(merkleRoot, index, operator, beneficiary, amount); } /// Allocates amount of KEEP for a given merkle root. /// @param merkleRoot Merkle root for a given interval. /// @param amount The amount of KEEP tokens allocated for the merkle root. function allocate(bytes32 merkleRoot, uint256 amount) public onlyOwner { token.safeTransferFrom(msg.sender, address(this), amount); merkleRoots[merkleRoot] = true; emit RewardsAllocated(merkleRoot, amount); } function isClaimed(bytes32 merkleRoot, uint256 index) public view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[merkleRoot][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(bytes32 merkleRoot, uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[merkleRoot][claimedWordIndex] = claimedBitMap[merkleRoot][claimedWordIndex] | (1 << claimedBitIndex); } } pragma solidity 0.5.17; import "@keep-network/keep-core/contracts/PhasedEscrow.sol"; /// @title ECDSARewardsEscrowBeneficiary /// @notice Transfer the received tokens from PhasedEscrow to a designated /// ECDSARewards contract. contract ECDSARewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } /// @title ECDSABackportRewardsEscrowBeneficiary /// @notice Trasfer the received tokens from Phased Escrow to a designated /// ECDSABackportRewards contract. contract ECDSABackportRewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./Escrow.sol"; interface IBeneficiaryContract { function __escrowSentTokens(uint256 amount) external; } /// @title PhasedEscrow /// @notice A token holder contract allowing contract owner to set beneficiary of /// tokens held by the contract and allowing the owner to withdraw the /// tokens to that beneficiary in phases. contract PhasedEscrow is Ownable { using SafeERC20 for IERC20; event BeneficiaryUpdated(address beneficiary); event TokensWithdrawn(address beneficiary, uint256 amount); IERC20 public token; IBeneficiaryContract public beneficiary; constructor(IERC20 _token) public { token = _token; } /// @notice Funds the escrow by transferring all of the approved tokens /// to the escrow. function receiveApproval( address _from, uint256 _value, address _token, bytes memory ) public { require(IERC20(_token) == token, "Unsupported token"); token.safeTransferFrom(_from, address(this), _value); } /// @notice Sets the provided address as a beneficiary allowing it to /// withdraw all tokens from escrow. This function can be called only /// by escrow owner. function setBeneficiary(IBeneficiaryContract _beneficiary) external onlyOwner { beneficiary = _beneficiary; emit BeneficiaryUpdated(address(beneficiary)); } /// @notice Withdraws the specified number of tokens from escrow to the /// beneficiary. If the beneficiary is not set, or there are /// insufficient tokens in escrow, the function fails. function withdraw(uint256 amount) external onlyOwner { require(address(beneficiary) != address(0), "Beneficiary not assigned"); uint256 balance = token.balanceOf(address(this)); require(amount <= balance, "Not enough tokens for withdrawal"); token.safeTransfer(address(beneficiary), amount); emit TokensWithdrawn(address(beneficiary), amount); beneficiary.__escrowSentTokens(amount); } /// @notice Withdraws all funds from a non-phased Escrow passed as /// a parameter. For this function to succeed, this PhasedEscrow /// has to be set as a beneficiary of the non-phased Escrow. function withdrawFromEscrow(Escrow _escrow) public { _escrow.withdraw(); } } interface ICurveRewards { function notifyRewardAmount(uint256 amount) external; } /// @title CurveRewardsEscrowBeneficiary /// @notice A beneficiary contract that can receive a withdrawal phase from a /// PhasedEscrow contract. Immediately stakes the received tokens on a /// designated CurveRewards contract. contract CurveRewardsEscrowBeneficiary is Ownable { IERC20 public token; ICurveRewards public curveRewards; constructor(IERC20 _token, ICurveRewards _curveRewards) public { token = _token; curveRewards = _curveRewards; } function __escrowSentTokens(uint256 amount) external onlyOwner { token.approve(address(curveRewards), amount); curveRewards.notifyRewardAmount(amount); } } /// @dev Interface of recipient contract for approveAndCall pattern. interface IStakerRewards { function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } /// @title StakerRewardsBeneficiary /// @notice An abstract beneficiary contract that can receive a withdrawal phase /// from a PhasedEscrow contract. The received tokens are immediately /// funded for a designated rewards escrow beneficiary contract. contract StakerRewardsBeneficiary is Ownable { IERC20 public token; IStakerRewards public stakerRewards; constructor(IERC20 _token, IStakerRewards _stakerRewards) public { token = _token; stakerRewards = _stakerRewards; } function __escrowSentTokens(uint256 amount) external onlyOwner { bool success = token.approve(address(stakerRewards), amount); require(success, "Token transfer approval failed"); stakerRewards.receiveApproval( address(this), amount, address(token), "" ); } } /// @title BeaconBackportRewardsEscrowBeneficiary /// @notice Transfer the received tokens to a designated /// BeaconBackportRewardsEscrowBeneficiary contract. contract BeaconBackportRewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } /// @title BeaconRewardsEscrowBeneficiary /// @notice Transfer the received tokens to a designated /// BeaconRewardsEscrowBeneficiary contract. contract BeaconRewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; // @title Escrow // @notice A token holder contract allowing contract owner to set beneficiary of // all tokens held by the contract and allowing the beneficiary to withdraw // the tokens. contract Escrow is Ownable { using SafeERC20 for IERC20; event BeneficiaryUpdated(address beneficiary); event TokensWithdrawn(address beneficiary, uint256 amount); IERC20 public token; address public beneficiary; constructor(IERC20 _token) public { token = _token; } // @notice Sets the provided address as a beneficiary allowing it to // withdraw all tokens from escrow. This function can be called only // by escrow owner. function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; emit BeneficiaryUpdated(beneficiary); } // @notice Withdraws all tokens from escrow to the beneficiary. // If the beneficiary is not set, caller is not the beneficiary, or there // are no tokens in escrow, function fails. function withdraw() public { require(beneficiary != address(0), "Beneficiary not assigned"); require(msg.sender == beneficiary, "Caller is not the beneficiary"); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "No tokens to withdraw"); token.safeTransfer(beneficiary, amount); emit TokensWithdrawn(beneficiary, amount); } } pragma solidity ^0.5.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; /// @dev Interface of recipient contract for approveAndCall pattern. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } /// @title KEEP Token /// @dev Standard ERC20Burnable token contract KeepToken is ERC20Burnable, ERC20Detailed { string public constant NAME = "KEEP Token"; string public constant SYMBOL = "KEEP"; uint8 public constant DECIMALS = 18; // The number of digits after the decimal place when displaying token values on-screen. uint256 public constant INITIAL_SUPPLY = 10**27; // 1 billion tokens, 18 decimal places. /// @dev Gives msg.sender all of existing tokens. constructor() public ERC20Detailed(NAME, SYMBOL, DECIMALS) { _mint(msg.sender, INITIAL_SUPPLY); } /// @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. /// @param _spender The address authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } } 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 aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } 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"; import "../../math/SafeMath.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } 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 "./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; } } /** β–“β–“β–Œ β–“β–“ ▐▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–„ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–„β–„β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▄▄▄▄ β–“β–“β–“β–“β–“β–“β–„β–„β–„β–„ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–€β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓▀▀▀▀ β–“β–“β–“β–“β–“β–“β–€β–€β–€β–€ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ β–“β–“β–“β–“β–“β–“ β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ Trust math, not hardware. */ pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./StakeDelegatable.sol"; import "./libraries/staking/MinimumStakeSchedule.sol"; import "./libraries/staking/GrantStaking.sol"; import "./libraries/staking/Locks.sol"; import "./libraries/staking/TopUps.sol"; import "./utils/PercentUtils.sol"; import "./utils/BytesLib.sol"; import "./Authorizations.sol"; import "./TokenStakingEscrow.sol"; import "./TokenSender.sol"; /// @title TokenStaking /// @notice A token staking contract for a specified standard ERC20Burnable token. /// A holder of the specified token can stake delegate its tokens to this contract /// and recover the stake after undelegation period is over. contract TokenStaking is Authorizations, StakeDelegatable { using BytesLib for bytes; using SafeMath for uint256; using PercentUtils for uint256; using SafeERC20 for ERC20Burnable; using GrantStaking for GrantStaking.Storage; using Locks for Locks.Storage; using TopUps for TopUps.Storage; event StakeDelegated( address indexed owner, address indexed operator ); event OperatorStaked( address indexed operator, address indexed beneficiary, address indexed authorizer, uint256 value ); event StakeOwnershipTransferred( address indexed operator, address indexed newOwner ); event TopUpInitiated(address indexed operator, uint256 topUp); event TopUpCompleted(address indexed operator, uint256 newAmount); event Undelegated(address indexed operator, uint256 undelegatedAt); event RecoveredStake(address operator); event TokensSlashed(address indexed operator, uint256 amount); event TokensSeized(address indexed operator, uint256 amount); event StakeLocked(address indexed operator, address lockCreator, uint256 until); event LockReleased(address indexed operator, address lockCreator); event ExpiredLockReleased(address indexed operator, address lockCreator); uint256 public deployedAt; uint256 public initializationPeriod; // varies between mainnet and testnet ERC20Burnable internal token; TokenGrant internal tokenGrant; TokenStakingEscrow internal escrow; GrantStaking.Storage internal grantStaking; Locks.Storage internal locks; TopUps.Storage internal topUps; uint256 internal constant twoWeeks = 1209600; // [sec] uint256 internal constant twoMonths = 5184000; // [sec] // 2020-04-28; the date of deploying KEEP token. // TX: 0xea22d72bc7de4c82798df7194734024a1f2fd57b173d0e065864ff4e9d3dc014 uint256 internal constant minimumStakeScheduleStart = 1588042366; /// @notice Creates a token staking contract for a provided Standard ERC20Burnable token. /// @param _token KEEP token contract. /// @param _tokenGrant KEEP token grant contract. /// @param _escrow Escrow dedicated for this staking contract. /// @param _registry Keep contract registry contract. /// @param _initializationPeriod To avoid certain attacks on work selection, recently created /// operators must wait for a specific period of time before being eligible for work selection. constructor( ERC20Burnable _token, TokenGrant _tokenGrant, TokenStakingEscrow _escrow, KeepRegistry _registry, uint256 _initializationPeriod ) Authorizations(_registry) public { token = _token; tokenGrant = _tokenGrant; escrow = _escrow; registry = _registry; initializationPeriod = _initializationPeriod; deployedAt = block.timestamp; } /// @notice Returns minimum amount of KEEP that allows sMPC cluster client to /// participate in the Keep network. Expressed as number with 18-decimal places. /// Initial minimum stake is higher than the final and lowered periodically based /// on the amount of steps and the length of the minimum stake schedule in seconds. function minimumStake() public view returns (uint256) { return MinimumStakeSchedule.current(minimumStakeScheduleStart); } /// @notice Returns the current value of the undelegation period. /// The staking contract guarantees that an undelegated operator’s stakes /// will stay locked for a period of time after undelegation, and thus /// available as collateral for any work the operator is engaged in. /// The undelegation period is two weeks for the first two months and /// two months after that. function undelegationPeriod() public view returns(uint256) { return block.timestamp < deployedAt.add(twoMonths) ? twoWeeks : twoMonths; } /// @notice Receives approval of token transfer and stakes the approved /// amount or adds the approved amount to an existing delegation (a β€œtop-up”). /// In case of a top-up, it is expected that the operator stake is not /// undelegated and that the top-up is performed from the same source of /// tokens as the initial delegation. That is, if the tokens were delegated /// from a grant, top-up has to be performed from the same grant. If the /// delegation was done using liquid tokens, only liquid tokens from the /// same owner can be used to top-up the stake. /// Top-up can not be cancelled so it is important to be careful with the /// amount of KEEP added to the stake. /// @dev Requires that the provided token contract be the same one linked to /// this contract. /// @param _from The owner of the tokens who approved them to transfer. /// @param _value Approved amount for the transfer and stake. /// @param _token Token contract address. /// @param _extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes), ignored for a top-up /// - Operator address (20 bytes) /// - Authorizer address (20 bytes), ignored for a top-up /// - Grant ID (32 bytes) - required only when called by TokenStakingEscrow function receiveApproval( address _from, uint256 _value, address _token, bytes memory _extraData ) public { require(ERC20Burnable(_token) == token, "Unrecognized token"); require(_extraData.length >= 60, "Corrupted delegation data"); // Transfer tokens to this contract. token.safeTransferFrom(_from, address(this), _value); address operator = _extraData.toAddress(20); // See if there is an existing delegation for this operator... if (operators[operator].packedParams.getCreationTimestamp() == 0) { // If there is no existing delegation, delegate tokens using // beneficiary and authorizer passed in _extraData. delegate(_from, _value, operator, _extraData); } else { // If there is an existing delegation, top-up the stake. topUp(_from, _value, operator, _extraData); } } /// @notice Delegates tokens to a new operator using beneficiary and /// authorizer passed in _extraData parameter. /// @param _from The owner of the tokens who approved them to transfer. /// @param _value Approved amount for the transfer and stake. /// @param _operator The new operator address. /// @param _extraData Data for stake delegation as passed to receiveApproval. function delegate( address _from, uint256 _value, address _operator, bytes memory _extraData ) internal { require(_value >= minimumStake(), "Less than the minimum stake"); address payable beneficiary = address(uint160(_extraData.toAddress(0))); address authorizer = _extraData.toAddress(40); operators[_operator] = Operator( OperatorParams.pack(_value, block.timestamp, 0), _from, beneficiary, authorizer ); grantStaking.tryCapturingDelegationData( tokenGrant, address(escrow), _from, _operator, _extraData ); emit StakeDelegated(_from, _operator); emit OperatorStaked(_operator, beneficiary, authorizer, _value); } /// @notice Performs top-up to an existing operator. Tokens added during /// stake initialization period are immediatelly added to the stake and /// stake initialization timer is reset to the current block. Tokens added /// in a top-up after the stake initialization period is over are not /// included in the operator stake until the initialization period for /// a top-up passes and top-up is committed. Operator must not have the stake /// undelegated. It is expected that the top-up is done from the same source /// of tokens as the initial delegation. That is, if the tokens were /// delegated from a grant, top-up has to be performed from the same grant. /// If the delegation was done using liquid tokens, only liquid tokens from /// the same owner can be used to top-up the stake. /// Top-up can not be cancelled so it is important to be careful with the /// amount of KEEP added to the stake. /// @param _from The owner of the tokens who approved them to transfer. /// @param _value Approved amount for the transfer and top-up to /// an existing stake. /// @param _operator The new operator address. /// @param _extraData Data for stake delegation as passed to receiveApproval function topUp( address _from, uint256 _value, address _operator, bytes memory _extraData ) internal { // Top-up comes from a grant if it's been initiated from TokenGrantStake // contract or if it's been initiated from TokenStakingEscrow by // redelegation. bool isFromGrant = address(tokenGrant.grantStakes(_operator)) == _from || address(escrow) == _from; if (grantStaking.hasGrantDelegated(_operator)) { // Operator has grant delegated. We need to see if the top-up // is performed also from a grant. require(isFromGrant, "Must be from a grant"); // If it is from a grant, we need to make sure it's from the same // grant as the original delegation. We do not want to mix unlocking // schedules. uint256 previousGrantId = grantStaking.getGrantForOperator(_operator); (, uint256 grantId) = grantStaking.tryCapturingDelegationData( tokenGrant, address(escrow), _from, _operator, _extraData ); require(grantId == previousGrantId, "Not the same grant"); } else { // Operator has no grant delegated. We need to see if the top-up // is performed from liquid tokens of the same owner. require(!isFromGrant, "Must not be from a grant"); require(operators[_operator].owner == _from, "Not the same owner"); } uint256 operatorParams = operators[_operator].packedParams; if (!_isInitialized(operatorParams)) { // If the stake is not yet initialized, we add tokens immediately // but we also reset stake initialization time counter. operators[_operator].packedParams = topUps.instantComplete( _value, _operator, operatorParams, escrow ); } else { // If the stake is initialized, we do NOT add tokens immediately. // We initiate the top-up and will add tokens to the stake only // after the initialization period for a top-up passes. topUps.initiate(_value, _operator, operatorParams, escrow); } } /// @notice Commits pending top-up for the provided operator. If the top-up /// did not pass the initialization period, the function fails. /// @param _operator The operator with a pending top-up that is getting /// committed. function commitTopUp(address _operator) public { operators[_operator].packedParams = topUps.commit( _operator, operators[_operator].packedParams, initializationPeriod ); } /// @notice Cancels stake of tokens within the operator initialization period /// without being subjected to the token lockup for the undelegation period. /// This can be used to undo mistaken delegation to the wrong operator address. /// @param _operator Address of the stake operator. function cancelStake(address _operator) public { address owner = operators[_operator].owner; require( msg.sender == owner || msg.sender == _operator || grantStaking.canUndelegate(_operator, tokenGrant), "Not authorized" ); uint256 operatorParams = operators[_operator].packedParams; require( !_isInitialized(operatorParams), "Initialized stake" ); uint256 amount = operatorParams.getAmount(); operators[_operator].packedParams = operatorParams.setAmount(0); transferOrDeposit(owner, _operator, amount); } /// @notice Undelegates staked tokens. You will be able to recover your stake by calling /// `recoverStake()` with operator address once undelegation period is over. /// @param _operator Address of the stake operator. function undelegate(address _operator) public { undelegateAt(_operator, block.timestamp); } /// @notice Set an undelegation time for staked tokens. /// Undelegation will begin at the specified timestamp. /// You will be able to recover your stake by calling /// `recoverStake()` with operator address once undelegation period is over. /// @param _operator Address of the stake operator. /// @param _undelegationTimestamp The timestamp undelegation is to start at. function undelegateAt( address _operator, uint256 _undelegationTimestamp ) public { require( msg.sender == _operator || msg.sender == operators[_operator].owner || grantStaking.canUndelegate(_operator, tokenGrant), "Not authorized" ); uint256 oldParams = operators[_operator].packedParams; require( _undelegationTimestamp >= block.timestamp && _undelegationTimestamp > oldParams.getCreationTimestamp().add(initializationPeriod), "Invalid timestamp" ); uint256 existingUndelegationTimestamp = oldParams.getUndelegationTimestamp(); require( // Undelegation not in progress OR existingUndelegationTimestamp == 0 || // Undelegating sooner than previously set time OR existingUndelegationTimestamp > _undelegationTimestamp || // We have already checked above that msg.sender is owner, grantee, // or operator. Only owner and grantee are eligible to postpone the // delegation so it is enough if we exclude operator here. msg.sender != _operator, "Operator may not postpone" ); operators[_operator].packedParams = oldParams.setUndelegationTimestamp( _undelegationTimestamp ); emit Undelegated(_operator, _undelegationTimestamp); } /// @notice Recovers staked tokens and transfers them back to the owner. /// Recovering tokens can only be performed when the operator finished /// undelegating. /// @param _operator Operator address. function recoverStake(address _operator) public { uint256 operatorParams = operators[_operator].packedParams; require( operatorParams.getUndelegationTimestamp() != 0, "Not undelegated" ); require( _isUndelegatingFinished(operatorParams), "Still undelegating" ); require( !isStakeLocked(_operator), "Locked stake" ); uint256 amount = operatorParams.getAmount(); // If there is a pending top-up, force-commit it before returning tokens. amount = amount.add(topUps.cancel(_operator)); operators[_operator].packedParams = operatorParams.setAmount(0); transferOrDeposit(operators[_operator].owner, _operator, amount); emit RecoveredStake(_operator); } /// @notice Gets stake delegation info for the given operator. /// @param _operator Operator address. /// @return amount The amount of tokens the given operator delegated. /// @return createdAt The time when the stake has been delegated. /// @return undelegatedAt The time when undelegation has been requested. /// If undelegation has not been requested, 0 is returned. function getDelegationInfo(address _operator) public view returns (uint256 amount, uint256 createdAt, uint256 undelegatedAt) { return operators[_operator].packedParams.unpack(); } /// @notice Locks given operator stake for the specified duration. /// Locked stake may not be recovered until the lock expires or is released, /// even if the normal undelegation period has passed. /// Only previously authorized operator contract can lock the stake. /// @param operator Operator address. /// @param duration Lock duration in seconds. function lockStake( address operator, uint256 duration ) public onlyApprovedOperatorContract(msg.sender) { require( isAuthorizedForOperator(operator, msg.sender), "Not authorized" ); uint256 operatorParams = operators[operator].packedParams; require( _isInitialized(operatorParams), "Inactive stake" ); require( !_isUndelegating(operatorParams), "Undelegating stake" ); locks.lockStake(operator, duration); } /// @notice Removes a lock the caller had previously placed on the operator. /// @dev Only for operator contracts. /// To remove expired or disabled locks, use `releaseExpiredLocks`. /// The authorization check ensures that the caller must have been able /// to place a lock on the operator sometime in the past. /// We don't need to check for current approval status of the caller /// because unlocking stake cannot harm the operator /// nor interfere with other operator contracts. /// Therefore even disabled operator contracts may freely unlock stake. /// @param operator Operator address. function unlockStake( address operator ) public { require( isAuthorizedForOperator(operator, msg.sender), "Not authorized" ); locks.releaseLock(operator); } /// @notice Removes the lock of the specified operator contract /// if the lock has expired or the contract has been disabled. /// @dev Necessary for removing locks placed by contracts /// that have been disabled by the panic button. /// Also applicable to prevent inadvertent DoS of `recoverStake` /// if too many operator contracts have failed to clean up their locks. function releaseExpiredLock( address operator, address operatorContract ) public { locks.releaseExpiredLock(operator, operatorContract, address(this)); } /// @notice Check whether the operator has any active locks /// that haven't expired yet /// and whose creators aren't disabled by the panic button. function isStakeLocked(address operator) public view returns (bool) { return locks.isStakeLocked(operator, address(this)); } /// @notice Get the locks placed on the operator. /// @return creators The addresses of operator contracts /// that have placed a lock on the operator. /// @return expirations The expiration times /// of the locks placed on the operator. function getLocks(address operator) public view returns (address[] memory creators, uint256[] memory expirations) { return locks.getLocks(operator); } /// @notice Slash provided token amount from every member in the misbehaved /// operators array and burn 100% of all the tokens. /// @param amountToSlash Token amount to slash from every misbehaved operator. /// @param misbehavedOperators Array of addresses to seize the tokens from. function slash(uint256 amountToSlash, address[] memory misbehavedOperators) public onlyApprovedOperatorContract(msg.sender) { uint256 totalAmountToBurn; address authoritySource = getAuthoritySource(msg.sender); for (uint i = 0; i < misbehavedOperators.length; i++) { address operator = misbehavedOperators[i]; require(authorizations[authoritySource][operator], "Not authorized"); uint256 operatorParams = operators[operator].packedParams; require( _isInitialized(operatorParams), "Inactive stake" ); require( !_isStakeReleased(operator, operatorParams, msg.sender), "Stake is released" ); uint256 currentAmount = operatorParams.getAmount(); if (currentAmount < amountToSlash) { totalAmountToBurn = totalAmountToBurn.add(currentAmount); operators[operator].packedParams = operatorParams.setAmount(0); emit TokensSlashed(operator, currentAmount); } else { totalAmountToBurn = totalAmountToBurn.add(amountToSlash); operators[operator].packedParams = operatorParams.setAmount( currentAmount.sub(amountToSlash) ); emit TokensSlashed(operator, amountToSlash); } } token.burn(totalAmountToBurn); } /// @notice Seize provided token amount from every member in the misbehaved /// operators array. The tattletale is rewarded with 5% of the total seized /// amount scaled by the reward adjustment parameter and the rest 95% is burned. /// @param amountToSeize Token amount to seize from every misbehaved operator. /// @param rewardMultiplier Reward adjustment in percentage. Min 1% and 100% max. /// @param tattletale Address to receive the 5% reward. /// @param misbehavedOperators Array of addresses to seize the tokens from. function seize( uint256 amountToSeize, uint256 rewardMultiplier, address tattletale, address[] memory misbehavedOperators ) public onlyApprovedOperatorContract(msg.sender) { uint256 totalAmountToBurn; address authoritySource = getAuthoritySource(msg.sender); for (uint i = 0; i < misbehavedOperators.length; i++) { address operator = misbehavedOperators[i]; require(authorizations[authoritySource][operator], "Not authorized"); uint256 operatorParams = operators[operator].packedParams; require( _isInitialized(operatorParams), "Inactive stake" ); require( !_isStakeReleased(operator, operatorParams, msg.sender), "Stake is released" ); uint256 currentAmount = operatorParams.getAmount(); if (currentAmount < amountToSeize) { totalAmountToBurn = totalAmountToBurn.add(currentAmount); operators[operator].packedParams = operatorParams.setAmount(0); emit TokensSeized(operator, currentAmount); } else { totalAmountToBurn = totalAmountToBurn.add(amountToSeize); operators[operator].packedParams = operatorParams.setAmount( currentAmount.sub(amountToSeize) ); emit TokensSeized(operator, amountToSeize); } } uint256 tattletaleReward = (totalAmountToBurn.percent(5)).percent(rewardMultiplier); token.safeTransfer(tattletale, tattletaleReward); token.burn(totalAmountToBurn.sub(tattletaleReward)); } /// @notice Allows the current staking relationship owner to transfer the /// ownership to someone else. /// @param operator Address of the stake operator. /// @param newOwner Address of the new staking relationship owner. function transferStakeOwnership(address operator, address newOwner) public { require(msg.sender == operators[operator].owner, "Not authorized"); operators[operator].owner = newOwner; emit StakeOwnershipTransferred(operator, newOwner); } /// @notice Gets the eligible stake balance of the specified address. /// An eligible stake is a stake that passed the initialization period /// and is not currently undelegating. Also, the operator had to approve /// the specified operator contract. /// /// Operator with a minimum required amount of eligible stake can join the /// network and participate in new work selection. /// /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. /// @return an uint256 representing the eligible stake balance. function eligibleStake( address _operator, address _operatorContract ) public view returns (uint256 balance) { uint256 operatorParams = operators[_operator].packedParams; // To be eligible for work selection, the operator must: // - have the operator contract authorized // - have the stake initialized // - must not be undelegating; keep in mind the `undelegatedAt` may be // set to a time in the future, to schedule undelegation in advance. // In this case the operator is still eligible until the timestamp // `undelegatedAt`. if ( isAuthorizedForOperator(_operator, _operatorContract) && _isInitialized(operatorParams) && !_isUndelegating(operatorParams) ) { balance = operatorParams.getAmount(); } } /// @notice Gets the active stake balance of the specified address. /// An active stake is a stake that passed the initialization period, /// and may be in the process of undelegation /// but has not been released yet, /// either because the undelegation period is not over, /// or because the operator contract has an active lock on the operator. /// Also, the operator had to approve the specified operator contract. /// /// The difference between eligible stake is that active stake does not make /// the operator eligible for work selection but it may be still finishing /// earlier work until the stake is released. /// Operator with a minimum required /// amount of active stake can join the network but cannot be selected to any /// new work. /// /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. /// @return an uint256 representing the eligible stake balance. function activeStake( address _operator, address _operatorContract ) public view returns (uint256 balance) { uint256 operatorParams = operators[_operator].packedParams; if ( isAuthorizedForOperator(_operator, _operatorContract) && _isInitialized(operatorParams) && !_isStakeReleased( _operator, operatorParams, _operatorContract ) ) { balance = operatorParams.getAmount(); } } /// @notice Checks if the specified account has enough active stake to become /// network operator and that the specified operator contract has been /// authorized for potential slashing. /// /// Having the required minimum of active stake makes the operator eligible /// to join the network. If the active stake is not currently undelegating, /// operator is also eligible for work selection. /// /// @param staker Staker's address /// @param operatorContract Operator contract's address /// @return True if has enough active stake to participate in the network, /// false otherwise. function hasMinimumStake( address staker, address operatorContract ) public view returns(bool) { return activeStake(staker, operatorContract) >= minimumStake(); } /// @notice Is the operator with the given params initialized function _isInitialized(uint256 _operatorParams) internal view returns (bool) { return block.timestamp > _operatorParams.getCreationTimestamp().add(initializationPeriod); } /// @notice Is the operator with the given params undelegating function _isUndelegating(uint256 _operatorParams) internal view returns (bool) { uint256 undelegatedAt = _operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt); } /// @notice Has the operator with the given params finished undelegating function _isUndelegatingFinished(uint256 _operatorParams) internal view returns (bool) { uint256 undelegatedAt = _operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt.add(undelegationPeriod())); } /// @notice Get whether the operator's stake is released /// as far as the operator contract is concerned. /// If the operator contract has a lock on the operator, /// the operator's stake is be released when the lock expires. /// Otherwise the stake is released when the operator finishes undelegating. function _isStakeReleased( address _operator, uint256 _operatorParams, address _operatorContract ) internal view returns (bool) { return _isUndelegatingFinished(_operatorParams) && locks.isStakeReleased(_operator, _operatorContract); } function transferOrDeposit( address _owner, address _operator, uint256 _amount ) internal { if (grantStaking.hasGrantDelegated(_operator)) { // For tokens staked from a grant, transfer them to the escrow. TokenSender(address(token)).approveAndCall( address(escrow), _amount, abi.encode(_operator, grantStaking.getGrantForOperator(_operator)) ); } else { // For liquid tokens staked, transfer them straight to the owner. token.safeTransfer(_owner, _amount); } } } /** β–“β–“β–Œ β–“β–“ ▐▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–„ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–„β–„β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▄▄▄▄ β–“β–“β–“β–“β–“β–“β–„β–„β–„β–„ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–€β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓▀▀▀▀ β–“β–“β–“β–“β–“β–“β–€β–€β–€β–€ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ β–“β–“β–“β–“β–“β–“ β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ Trust math, not hardware. */ pragma solidity 0.5.17; import "./utils/OperatorParams.sol"; /// @title Stake Delegatable /// @notice A base contract to allow stake delegation for staking contracts. contract StakeDelegatable { using OperatorParams for uint256; mapping(address => Operator) internal operators; struct Operator { uint256 packedParams; address owner; address payable beneficiary; address authorizer; } /// @notice Gets the stake balance of the specified address. /// @param _address The address to query the balance of. /// @return An uint256 representing the amount staked by the passed address. function balanceOf(address _address) public view returns (uint256 balance) { return operators[_address].packedParams.getAmount(); } /// @notice Gets the stake owner for the specified operator address. /// @return Stake owner address. function ownerOf(address _operator) public view returns (address) { return operators[_operator].owner; } /// @notice Gets the beneficiary for the specified operator address. /// @return Beneficiary address. function beneficiaryOf(address _operator) public view returns (address payable) { return operators[_operator].beneficiary; } /// @notice Gets the authorizer for the specified operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address) { return operators[_operator].authorizer; } } pragma solidity 0.5.17; library OperatorParams { // OperatorParams packs values that are commonly used together // into a single uint256 to reduce the cost functions // like querying eligibility. // // An OperatorParams uint256 contains: // - the operator's staked token amount (uint128) // - the operator's creation timestamp (uint64) // - the operator's undelegation timestamp (uint64) // // These are packed as [amount | createdAt | undelegatedAt] // // Staked KEEP is stored in an uint128, // which is sufficient because KEEP tokens have 18 decimals (2^60) // and there will be at most 10^9 KEEP in existence (2^30). // // Creation and undelegation times are stored in an uint64 each. // Thus uint64s would be sufficient for around 3*10^11 years. uint256 constant TIMESTAMP_WIDTH = 64; uint256 constant AMOUNT_WIDTH = 128; uint256 constant TIMESTAMP_MAX = (2**TIMESTAMP_WIDTH) - 1; uint256 constant AMOUNT_MAX = (2**AMOUNT_WIDTH) - 1; uint256 constant CREATION_SHIFT = TIMESTAMP_WIDTH; uint256 constant AMOUNT_SHIFT = 2 * TIMESTAMP_WIDTH; function pack( uint256 amount, uint256 createdAt, uint256 undelegatedAt ) internal pure returns (uint256) { // Check for staked amount overflow. // We shouldn't actually ever need this. require( amount <= AMOUNT_MAX, "uint128 overflow" ); // Bitwise OR the timestamps together. // The resulting number is equal or greater than either, // and tells if we have a bit set outside the 64 available bits. require( (createdAt | undelegatedAt) <= TIMESTAMP_MAX, "uint64 overflow" ); return (amount << AMOUNT_SHIFT | createdAt << CREATION_SHIFT | undelegatedAt); } function unpack(uint256 packedParams) internal pure returns ( uint256 amount, uint256 createdAt, uint256 undelegatedAt ) { amount = getAmount(packedParams); createdAt = getCreationTimestamp(packedParams); undelegatedAt = getUndelegationTimestamp(packedParams); } function getAmount(uint256 packedParams) internal pure returns (uint256) { return (packedParams >> AMOUNT_SHIFT) & AMOUNT_MAX; } function setAmount( uint256 packedParams, uint256 amount ) internal pure returns (uint256) { return pack( amount, getCreationTimestamp(packedParams), getUndelegationTimestamp(packedParams) ); } function getCreationTimestamp(uint256 packedParams) internal pure returns (uint256) { return (packedParams >> CREATION_SHIFT) & TIMESTAMP_MAX; } function setCreationTimestamp( uint256 packedParams, uint256 creationTimestamp ) internal pure returns (uint256) { return pack( getAmount(packedParams), creationTimestamp, getUndelegationTimestamp(packedParams) ); } function getUndelegationTimestamp(uint256 packedParams) internal pure returns (uint256) { return packedParams & TIMESTAMP_MAX; } function setUndelegationTimestamp( uint256 packedParams, uint256 undelegationTimestamp ) internal pure returns (uint256) { return pack( getAmount(packedParams), getCreationTimestamp(packedParams), undelegationTimestamp ); } function setAmountAndCreationTimestamp( uint256 packedParams, uint256 amount, uint256 creationTimestamp ) internal pure returns (uint256) { return pack( amount, creationTimestamp, getUndelegationTimestamp(packedParams) ); } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @notice MinimumStakeSchedule defines the minimum stake parametrization and /// schedule. It starts with a minimum stake of 100k KEEP. Over the following /// 2 years, the minimum stake is lowered periodically using a uniform stepwise /// function, eventually ending at 10k. library MinimumStakeSchedule { using SafeMath for uint256; // 2 years in seconds (seconds per day * days in a year * years) uint256 public constant schedule = 86400 * 365 * 2; uint256 public constant steps = 10; uint256 public constant base = 10000 * 1e18; /// @notice Returns the current value of the minimum stake. The minimum /// stake is lowered periodically over the course of 2 years since the time /// of the shedule start and eventually ends at 10k KEEP. function current(uint256 scheduleStart) internal view returns (uint256) { if (now < scheduleStart.add(schedule)) { uint256 currentStep = steps.mul(now.sub(scheduleStart)).div(schedule); return base.mul(steps.sub(currentStep)); } return base; } } pragma solidity 0.5.17; import "../../TokenGrant.sol"; import "../../TokenStakingEscrow.sol"; import "../..//utils/BytesLib.sol"; import "../RolesLookup.sol"; /// @notice TokenStaking contract library allowing to capture the details of /// delegated grants and offering functions allowing to check grantee /// authentication for stake delegation management. library GrantStaking { using BytesLib for bytes; using RolesLookup for address payable; /// @dev Grant ID is flagged with the most significant bit set, to /// distinguish the grant ID `0` from default (null) value. The flag is /// toggled with bitwise XOR (`^`) which keeps all other bits intact but /// flips the flag bit. The flag should be set before writing to /// `operatorToGrant`, and unset after reading from `operatorToGrant` /// before using the value. uint256 constant GRANT_ID_FLAG = 1 << 255; struct Storage { /// @dev Do not read or write this mapping directly; please use /// `hasGrantDelegated`, `setGrantForOperator`, and `getGrantForOperator` /// instead. mapping (address => uint256) _operatorToGrant; } /// @notice Tries to capture delegation data if the pending delegation has /// been created from a grant. There are only two possibilities and they /// need to be handled differently: delegation comes from the TokenGrant /// contract or delegation comes from TokenStakingEscrow. In those two cases /// grant ID has to be captured in a different way. /// @dev In case of a delegation from the escrow, it is expected that grant /// ID is passed in extraData bytes array. When the delegation comes from /// the TokenGrant contract, delegation data are obtained directly from that /// contract using `tryCapturingGrantId` function. /// @param tokenGrant KEEP token grant contract reference. /// @param escrow TokenStakingEscrow contract address. /// @param from The owner of the tokens who approved them to transfer. /// @param operator The operator tokens are delegated to. /// @param extraData Data for stake delegation, as passed to /// `receiveApproval` of `TokenStaking`. function tryCapturingDelegationData( Storage storage self, TokenGrant tokenGrant, address escrow, address from, address operator, bytes memory extraData ) public returns (bool, uint256) { if (from == escrow) { require(extraData.length == 92, "Corrupted delegation data from escrow"); uint256 grantId = extraData.toUint(60); setGrantForOperator(self, operator, grantId); return (true, grantId); } else { return tryCapturingGrantId(self, tokenGrant, operator); } } /// @notice Checks if the delegation for the given operator has been created /// from a grant defined in the passed token grant contract and if so, /// captures the grant ID for that delegation. /// Grant ID can be later retrieved based on the operator address and used /// to authenticate grantee or to fetch the information about grant /// unlocking schedule for escrow. /// @param tokenGrant KEEP token grant contract reference. /// @param operator The operator tokens are delegated to. function tryCapturingGrantId( Storage storage self, TokenGrant tokenGrant, address operator ) internal returns (bool, uint256) { (bool success, bytes memory data) = address(tokenGrant).call( abi.encodeWithSignature("getGrantStakeDetails(address)", operator) ); if (success) { (uint256 grantId,,address grantStakingContract) = abi.decode( data, (uint256, uint256, address) ); // Double-check if the delegation in TokenGrant has been defined // for this staking contract. If not, it means it's an old // delegation and the current one does not come from a grant. // The scenario covered here is: // - grantee delegated to operator A from a TokenGrant using another // staking contract, // - someone delegates to operator A using liquid tokens and this // staking contract. // Without this check, we'd consider the second delegation as coming // from a grant. if (address(this) != grantStakingContract) { return (false, 0); } setGrantForOperator(self, operator, grantId); return (true, grantId); } return (false, 0); } /// @notice Returns true if the given operator operates on stake delegated /// from a grant. false is returned otherwise. /// @param operator The operator to which tokens from a grant are /// potentially delegated to. function hasGrantDelegated( Storage storage self, address operator ) public view returns (bool) { return self._operatorToGrant[operator] != 0; } /// @notice Associates operator with the provided grant ID. It means that /// the given operator delegates on stake from the grant with this ID. /// @param operator The operator tokens are delegate to. /// @param grantId Identifier of a grant from which the tokens are delegated /// to. function setGrantForOperator( Storage storage self, address operator, uint256 grantId ) public { self._operatorToGrant[operator] = grantId ^ GRANT_ID_FLAG; } /// @notice Returns grant ID for the provided operator. If the operator /// does not operate on stake delegated from a grant, function reverts. /// @dev To avoid reverting in case the grant ID for the operator does not /// exist, consider calling hasGrantDelegated before. /// @param operator The operator tokens are delegate to. function getGrantForOperator( Storage storage self, address operator ) public view returns (uint256) { uint256 grantId = self._operatorToGrant[operator]; require (grantId != 0, "No grant for the operator"); return grantId ^ GRANT_ID_FLAG; } /// @notice Returns true if msg.sender is grantee eligible to trigger stake /// undelegation for this operator. Function checks both standard grantee /// and managed grantee case. /// @param operator The operator tokens are delegated to. /// @param tokenGrant KEEP token grant contract reference. function canUndelegate( Storage storage self, address operator, TokenGrant tokenGrant ) public returns (bool) { // First of all, we need to see if the operator has grant delegated. // If not, we don't need to bother about checking grantee or // managed grantee and we just return false. if (!hasGrantDelegated(self, operator)) { return false; } uint256 grantId = getGrantForOperator(self, operator); (,,,,uint256 revokedAt, address grantee) = tokenGrant.getGrant(grantId); // Is msg.sender grantee of a standard grant? if (msg.sender == grantee) { return true; } // If not, we need to dig deeper and see if we are dealing with // a grantee from a managed grant. if ((msg.sender).isManagedGranteeForGrant(grantId, tokenGrant)) { return true; } // There is only one possibility left - grant has been revoked and // grant manager wants to take back delegated tokens. if (revokedAt == 0) { return false; } (address grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId); return msg.sender == grantManager; } } /** β–“β–“β–Œ β–“β–“ ▐▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–„ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–„β–„β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▄▄▄▄ β–“β–“β–“β–“β–“β–“β–„β–„β–„β–„ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–€β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓▀▀▀▀ β–“β–“β–“β–“β–“β–“β–€β–€β–€β–€ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ β–“β–“β–“β–“β–“β–“ β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ Trust math, not hardware. */ pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/grant/UnlockingSchedule.sol"; import "./utils/BytesLib.sol"; import "./KeepToken.sol"; import "./utils/BytesLib.sol"; import "./TokenGrant.sol"; import "./ManagedGrant.sol"; import "./TokenSender.sol"; /// @title TokenStakingEscrow /// @notice Escrow lets the staking contract to deposit undelegated, granted /// tokens and either withdraw them based on the grant unlocking schedule or /// re-delegate them to another operator. /// @dev The owner of TokenStakingEscrow is TokenStaking contract and only owner /// can deposit. This contract works with an assumption that operator is unique /// in the scope of `TokenStaking`, that is, no more than one delegation in the /// `TokenStaking` can be done do the given operator ever. Even if the previous /// delegation ended, operator address cannot be reused. contract TokenStakingEscrow is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; using BytesLib for bytes; using UnlockingSchedule for uint256; event Deposited( address indexed operator, uint256 indexed grantId, uint256 amount ); event DepositRedelegated( address indexed previousOperator, address indexed newOperator, uint256 indexed grantId, uint256 amount ); event DepositWithdrawn( address indexed operator, address indexed grantee, uint256 amount ); event RevokedDepositWithdrawn( address indexed operator, address indexed grantManager, uint256 amount ); event EscrowAuthorized( address indexed grantManager, address escrow ); IERC20 public keepToken; TokenGrant public tokenGrant; struct Deposit { uint256 grantId; uint256 amount; uint256 withdrawn; uint256 redelegated; } // operator address -> KEEP deposit mapping(address => Deposit) internal deposits; // Other escrows authorized by grant manager. Grantee may request to migrate // tokens to another authorized escrow. // grant manager -> escrow -> authorized? mapping(address => mapping (address => bool)) internal authorizedEscrows; constructor( KeepToken _keepToken, TokenGrant _tokenGrant ) public { keepToken = _keepToken; tokenGrant = _tokenGrant; } /// @notice receiveApproval accepts deposits from staking contract and /// stores them in the escrow by the operator address from which they were /// undelegated. Function expects operator address and grant identifier to /// be passed as ABI-encoded information in extraData. Grant with the given /// identifier has to exist. /// @param from Address depositing tokens - it has to be the address of /// TokenStaking contract owning TokenStakingEscrow. /// @param value The amount of KEEP tokens deposited. /// @param token The address of KEEP token contract. /// @param extraData ABI-encoded data containing operator address (32 bytes) /// and grant ID (32 bytes). function receiveApproval( address from, uint256 value, address token, bytes memory extraData ) public { require(IERC20(token) == keepToken, "Not a KEEP token"); require(msg.sender == token, "KEEP token is not the sender"); require(extraData.length == 64, "Unexpected data length"); (address operator, uint256 grantId) = abi.decode( extraData, (address, uint256) ); receiveDeposit(from, value, operator, grantId); } /// @notice Redelegates deposit or part of the deposit to another operator. /// Uses the same staking contract as the original delegation. /// @param previousOperator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. /// @dev Only grantee is allowed to call this function. For managed grant, /// caller has to be the managed grantee. /// @param amount Amount of tokens to delegate. /// @param extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes) /// - Operator address (20 bytes) /// - Authorizer address (20 bytes) function redelegate( address previousOperator, uint256 amount, bytes memory extraData ) public { require(extraData.length == 60, "Corrupted delegation data"); Deposit memory deposit = deposits[previousOperator]; uint256 grantId = deposit.grantId; address newOperator = extraData.toAddress(20); require(isGrantee(msg.sender, grantId), "Not authorized"); require(getAmountRevoked(grantId) == 0, "Grant revoked"); require( availableAmount(previousOperator) >= amount, "Insufficient balance" ); require( !hasDeposit(newOperator), "Redelegating to previously used operator is not allowed" ); deposits[previousOperator].redelegated = deposit.redelegated.add(amount); TokenSender(address(keepToken)).approveAndCall( owner(), // TokenStaking contract associated with the escrow amount, abi.encodePacked(extraData, grantId) ); emit DepositRedelegated( previousOperator, newOperator, grantId, amount ); } /// @notice Returns true if there is a deposit for the given operator in /// the escrow. Otherwise, returns false. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function hasDeposit(address operator) public view returns (bool) { return depositedAmount(operator) > 0; } /// @notice Returns the currently available amount deposited in the escrow /// that may or may not be currently withdrawable. The available amount /// is the amount initially deposited minus the amount withdrawn and /// redelegated so far from that deposit. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function availableAmount(address operator) public view returns (uint256) { Deposit memory deposit = deposits[operator]; return deposit.amount.sub(deposit.withdrawn).sub(deposit.redelegated); } /// @notice Returns the total amount deposited in the escrow after /// undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositedAmount(address operator) public view returns (uint256) { return deposits[operator].amount; } /// @notice Returns grant ID for the amount deposited in the escrow after /// undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositGrantId(address operator) public view returns (uint256) { return deposits[operator].grantId; } /// @notice Returns the amount withdrawn so far from the value deposited /// in the escrow contract after undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositWithdrawnAmount(address operator) public view returns (uint256) { return deposits[operator].withdrawn; } /// @notice Returns the total amount redelegated so far from the value /// deposited in the escrow contract after undelegating it from the provided /// operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositRedelegatedAmount(address operator) public view returns (uint256) { return deposits[operator].redelegated; } /// @notice Returns the currently withdrawable amount that was previously /// deposited in the escrow after undelegating it from the provided operator. /// Tokens are unlocked based on their grant unlocking schedule. /// Function returns 0 for non-existing deposits and revoked grants if they /// have been revoked before they fully unlocked. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawable(address operator) public view returns (uint256) { Deposit memory deposit = deposits[operator]; // Staked tokens can be only withdrawn by grantee for non-revoked grant // assuming that grant has not fully unlocked before it's been // revoked. // // It is not possible for the escrow to determine the number of tokens // it should return to the grantee of a revoked grant given different // possible staking contracts and staking policies. // // If the entire grant unlocked before it's been reverted, escrow // lets to withdraw the entire deposited amount. if (getAmountRevoked(deposit.grantId) == 0) { ( uint256 duration, uint256 start, uint256 cliff ) = getUnlockingSchedule(deposit.grantId); uint256 unlocked = now.getUnlockedAmount( deposit.amount, duration, start, cliff ); if (deposit.withdrawn.add(deposit.redelegated) < unlocked) { return unlocked.sub(deposit.withdrawn).sub(deposit.redelegated); } } return 0; } /// @notice Withdraws currently unlocked tokens deposited in the escrow /// after undelegating them from the provided operator. Only grantee or /// operator can call this function. Important: this function can not be /// called for a `ManagedGrant` grantee. This may lead to locking tokens. /// For `ManagedGrant`, please use `withdrawToManagedGrantee` instead. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdraw(address operator) public { Deposit memory deposit = deposits[operator]; address grantee = getGrantee(deposit.grantId); // Make sure this function is not called for a managed grant. // If called for a managed grant, tokens could be locked there. // Better be safe than sorry. (bool success, ) = address(this).call( abi.encodeWithSignature("getManagedGrantee(address)", grantee) ); require(!success, "Can not be called for managed grant"); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); } /// @notice Withdraws currently unlocked tokens deposited in the escrow /// after undelegating them from the provided operator. Only grantee or /// operator can call this function. This function works only for /// `ManagedGrant` grantees. For a standard grant, please use `withdraw` /// instead. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawToManagedGrantee(address operator) public { Deposit memory deposit = deposits[operator]; address managedGrant = getGrantee(deposit.grantId); address grantee = getManagedGrantee(managedGrant); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); } /// @notice Migrates all available tokens to another authorized escrow. /// Can be requested only by grantee. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. /// @param receivingEscrow Escrow to which tokens should be migrated. /// @dev The receiving escrow needs to accept deposits from this escrow, at /// least for the period of migration. function migrate( address operator, address receivingEscrow ) public { Deposit memory deposit = deposits[operator]; require(isGrantee(msg.sender, deposit.grantId), "Not authorized"); address grantManager = getGrantManager(deposit.grantId); require( authorizedEscrows[grantManager][receivingEscrow], "Escrow not authorized" ); uint256 amountLeft = availableAmount(operator); deposits[operator].withdrawn = deposit.withdrawn.add(amountLeft); TokenSender(address(keepToken)).approveAndCall( receivingEscrow, amountLeft, abi.encode(operator, deposit.grantId) ); } /// @notice Withdraws the entire amount that is still deposited in the /// escrow in case the grant has been revoked. Anyone can call this function /// and the entire amount is transferred back to the grant manager. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawRevoked(address operator) public { Deposit memory deposit = deposits[operator]; require( getAmountRevoked(deposit.grantId) > 0, "No revoked tokens to withdraw" ); address grantManager = getGrantManager(deposit.grantId); withdrawRevoked(deposit, operator, grantManager); } /// @notice Used by grant manager to authorize another escrows for // funds migration. function authorizeEscrow(address anotherEscrow) public { require( anotherEscrow != address(0x0), "Escrow address can't be zero" ); authorizedEscrows[msg.sender][anotherEscrow] = true; emit EscrowAuthorized(msg.sender, anotherEscrow); } /// @notice Resolves the final grantee of ManagedGrant contract. If the /// provided address is not a ManagedGrant contract, function reverts. /// @param managedGrant Address of the managed grant contract. function getManagedGrantee( address managedGrant ) public view returns(address) { ManagedGrant grant = ManagedGrant(managedGrant); return grant.grantee(); } function receiveDeposit( address from, uint256 value, address operator, uint256 grantId ) internal { // This contract works with an assumption that operator is unique. // This is fine as long as the staking contract works with the same // assumption so we are limiting deposits to the staking contract only. require(from == owner(), "Only owner can deposit"); require( getAmountGranted(grantId) > 0, "Grant with this ID does not exist" ); require( !hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); keepToken.safeTransferFrom(from, address(this), value); deposits[operator] = Deposit(grantId, value, 0, 0); emit Deposited(operator, grantId, value); } function isGrantee( address maybeGrantee, uint256 grantId ) internal returns (bool) { // Let's check the simplest case first - standard grantee. // If the given address is set as a grantee for grant with the given ID, // we return true. address grantee = getGrantee(grantId); if (maybeGrantee == grantee) { return true; } // If the given address is not a standard grantee, there is still // a chance that address is a managed grantee. We are calling // getManagedGrantee that will cast the grantee to ManagedGrant and try // to call getGrantee() function. If this call returns non-zero address, // it means we are dealing with a ManagedGrant. (, bytes memory result) = address(this).call( abi.encodeWithSignature("getManagedGrantee(address)", grantee) ); if (result.length == 0) { return false; } // At this point we know we are dealing with a ManagedGrant, so the last // thing we need to check is whether the managed grantee of that grant // is the grantee address passed as a parameter. address managedGrantee = abi.decode(result, (address)); return maybeGrantee == managedGrantee; } function withdraw( Deposit memory deposit, address operator, address grantee ) internal { uint256 amount = withdrawable(operator); deposits[operator].withdrawn = deposit.withdrawn.add(amount); keepToken.safeTransfer(grantee, amount); emit DepositWithdrawn(operator, grantee, amount); } function withdrawRevoked( Deposit memory deposit, address operator, address grantManager ) internal { uint256 amount = availableAmount(operator); deposits[operator].withdrawn = amount; keepToken.safeTransfer(grantManager, amount); emit RevokedDepositWithdrawn(operator, grantManager, amount); } function getAmountGranted(uint256 grantId) internal view returns ( uint256 amountGranted ) { (amountGranted,,,,,) = tokenGrant.getGrant(grantId); } function getAmountRevoked(uint256 grantId) internal view returns ( uint256 amountRevoked ) { (,,,amountRevoked,,) = tokenGrant.getGrant(grantId); } function getUnlockingSchedule(uint256 grantId) internal view returns ( uint256 duration, uint256 start, uint256 cliff ) { (,duration,start,cliff,) = tokenGrant.getGrantUnlockingSchedule(grantId); } function getGrantee(uint256 grantId) internal view returns ( address grantee ) { (,,,,,grantee) = tokenGrant.getGrant(grantId); } function getGrantManager(uint256 grantId) internal view returns ( address grantManager ) { (grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId); } } pragma solidity ^0.5.4; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./TokenGrant.sol"; /// @title ManagedGrant /// @notice A managed grant acts as the grantee towards the token grant contract, /// proxying instructions from the actual grantee. /// The address used by the actual grantee /// to issue instructions and withdraw tokens /// can be reassigned with the consent of the grant manager. contract ManagedGrant { using SafeERC20 for ERC20Burnable; ERC20Burnable public token; TokenGrant public tokenGrant; address public grantManager; uint256 public grantId; address public grantee; address public requestedNewGrantee; event GranteeReassignmentRequested( address newGrantee ); event GranteeReassignmentConfirmed( address oldGrantee, address newGrantee ); event GranteeReassignmentCancelled( address cancelledRequestedGrantee ); event GranteeReassignmentChanged( address previouslyRequestedGrantee, address newRequestedGrantee ); event TokensWithdrawn( address destination, uint256 amount ); constructor( address _tokenAddress, address _tokenGrant, address _grantManager, uint256 _grantId, address _grantee ) public { token = ERC20Burnable(_tokenAddress); tokenGrant = TokenGrant(_tokenGrant); grantManager = _grantManager; grantId = _grantId; grantee = _grantee; } /// @notice Request a reassignment of the grantee address. /// Can only be called by the grantee. /// @param _newGrantee The requested new grantee. function requestGranteeReassignment(address _newGrantee) public onlyGrantee noRequestedReassignment { _setRequestedNewGrantee(_newGrantee); emit GranteeReassignmentRequested(_newGrantee); } /// @notice Cancel a pending grantee reassignment request. /// Can only be called by the grantee. function cancelReassignmentRequest() public onlyGrantee withRequestedReassignment { address cancelledGrantee = requestedNewGrantee; requestedNewGrantee = address(0); emit GranteeReassignmentCancelled(cancelledGrantee); } /// @notice Change a pending reassignment request to a different grantee. /// Can only be called by the grantee. /// @param _newGrantee The address of the new requested grantee. function changeReassignmentRequest(address _newGrantee) public onlyGrantee withRequestedReassignment { address previouslyRequestedGrantee = requestedNewGrantee; require( previouslyRequestedGrantee != _newGrantee, "Unchanged reassignment request" ); _setRequestedNewGrantee(_newGrantee); emit GranteeReassignmentChanged(previouslyRequestedGrantee, _newGrantee); } /// @notice Confirm a grantee reassignment request and set the new grantee as the grantee. /// Can only be called by the grant manager. /// @param _newGrantee The address of the new grantee. /// Must match the currently requested new grantee. function confirmGranteeReassignment(address _newGrantee) public onlyManager withRequestedReassignment { address oldGrantee = grantee; require( requestedNewGrantee == _newGrantee, "Reassignment address mismatch" ); grantee = requestedNewGrantee; requestedNewGrantee = address(0); emit GranteeReassignmentConfirmed(oldGrantee, _newGrantee); } /// @notice Withdraw all unlocked tokens from the grant. function withdraw() public onlyGrantee { require( requestedNewGrantee == address(0), "Can not withdraw with pending reassignment" ); tokenGrant.withdraw(grantId); uint256 amount = token.balanceOf(address(this)); token.safeTransfer(grantee, amount); emit TokensWithdrawn(grantee, amount); } /// @notice Stake tokens from the grant. /// @param _stakingContract The contract to stake the tokens on. /// @param _amount The amount of tokens to stake. /// @param _extraData Data for the stake delegation. /// This byte array must have the following values concatenated: /// beneficiary address (20 bytes) /// operator address (20 bytes) /// authorizer address (20 bytes) function stake( address _stakingContract, uint256 _amount, bytes memory _extraData ) public onlyGrantee { tokenGrant.stake(grantId, _stakingContract, _amount, _extraData); } /// @notice Cancel delegating tokens to the given operator. function cancelStake(address _operator) public onlyGranteeOr(_operator) { tokenGrant.cancelStake(_operator); } /// @notice Begin undelegating tokens from the given operator. function undelegate(address _operator) public onlyGranteeOr(_operator) { tokenGrant.undelegate(_operator); } /// @notice Recover tokens previously staked and delegated to the operator. function recoverStake(address _operator) public { tokenGrant.recoverStake(_operator); } function _setRequestedNewGrantee(address _newGrantee) internal { require(_newGrantee != address(0), "Invalid new grantee address"); require(_newGrantee != grantee, "New grantee same as current grantee"); requestedNewGrantee = _newGrantee; } modifier withRequestedReassignment { require( requestedNewGrantee != address(0), "No reassignment requested" ); _; } modifier noRequestedReassignment { require( requestedNewGrantee == address(0), "Reassignment already requested" ); _; } modifier onlyGrantee { require( msg.sender == grantee, "Only grantee may perform this action" ); _; } modifier onlyGranteeOr(address _operator) { require( msg.sender == grantee || msg.sender == _operator, "Only grantee or operator may perform this action" ); _; } modifier onlyManager { require( msg.sender == grantManager, "Only grantManager may perform this action" ); _; } } pragma solidity 0.5.17; /// @dev Interface of sender contract for approveAndCall pattern. interface TokenSender { function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external; } pragma solidity 0.5.17; import "../utils/AddressArrayUtils.sol"; import "../StakeDelegatable.sol"; import "../TokenGrant.sol"; import "../ManagedGrant.sol"; /// @title Roles Lookup /// @notice Library facilitating lookup of roles in stake delegation setup. library RolesLookup { using AddressArrayUtils for address[]; /// @notice Returns true if the tokenOwner delegated tokens to operator /// using the provided stakeDelegatable contract. Othwerwise, returns false. /// This function works only for the case when tokenOwner own those tokens /// and those are not tokens from a grant. function isTokenOwnerForOperator( address tokenOwner, address operator, StakeDelegatable stakeDelegatable ) internal view returns (bool) { return stakeDelegatable.ownerOf(operator) == tokenOwner; } /// @notice Returns true if the grantee delegated tokens to operator /// with the provided tokenGrant contract. Otherwise, returns false. /// This function works only for the case when tokens were generated from /// a non-managed grant, that is, the grantee is a non-contract address to /// which the delegated tokens were granted. /// @dev This function does not validate the staking reltionship on /// a particular staking contract. It only checks whether the grantee /// staked at least one time with the given operator. If you are interested /// in a particular token staking contract, you need to perform additional /// check. function isGranteeForOperator( address grantee, address operator, TokenGrant tokenGrant ) internal view returns (bool) { address[] memory operators = tokenGrant.getGranteeOperators(grantee); return operators.contains(operator); } /// @notice Returns true if the grantee from the given managed grant contract /// delegated tokens to operator with the provided tokenGrant contract. /// Otherwise, returns false. In case the grantee declared by the managed /// grant contract does not match the provided grantee, function reverts. /// This function works only for cases when grantee, from TokenGrant's /// perspective, is a smart contract exposing grantee() function returning /// the final grantee. One possibility is the ManagedGrant contract. /// @dev This function does not validate the staking reltionship on /// a particular staking contract. It only checks whether the grantee /// staked at least one time with the given operator. If you are interested /// in a particular token staking contract, you need to perform additional /// check. function isManagedGranteeForOperator( address grantee, address operator, address managedGrantContract, TokenGrant tokenGrant ) internal view returns (bool) { require( ManagedGrant(managedGrantContract).grantee() == grantee, "Not a grantee of the provided contract" ); address[] memory operators = tokenGrant.getGranteeOperators( managedGrantContract ); return operators.contains(operator); } /// @notice Returns true if grant with the given ID has been created with /// managed grant pointing currently to the grantee passed as a parameter. /// @dev The function does not revert if grant has not been created with /// a managed grantee. This function is not a view because it uses low-level /// call to check if the grant has been created with a managed grant. /// It does not however modify any state. function isManagedGranteeForGrant( address grantee, uint256 grantId, TokenGrant tokenGrant ) internal returns (bool) { (,,,,, address managedGrant) = tokenGrant.getGrant(grantId); (, bytes memory result) = managedGrant.call( abi.encodeWithSignature("grantee()") ); if (result.length == 0) { return false; } address managedGrantee = abi.decode(result, (address)); return grantee == managedGrantee; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { AuthorityVerifier } from "../../Authorizations.sol"; import "./LockUtils.sol"; library Locks { using SafeMath for uint256; using LockUtils for LockUtils.LockSet; event StakeLocked(address indexed operator, address lockCreator, uint256 until); event LockReleased(address indexed operator, address lockCreator); event ExpiredLockReleased(address indexed operator, address lockCreator); uint256 public constant maximumLockDuration = 86400 * 200; // 200 days in seconds struct Storage { // Locks placed on the operator. // `operatorLocks[operator]` returns all locks placed on the operator. // Each authorized operator contract can place one lock on an operator. mapping(address => LockUtils.LockSet) operatorLocks; } function lockStake( Storage storage self, address operator, uint256 duration ) public { require(duration <= maximumLockDuration, "Lock duration too long"); self.operatorLocks[operator].setLock( msg.sender, uint96(block.timestamp.add(duration)) ); emit StakeLocked(operator, msg.sender, block.timestamp.add(duration)); } function releaseLock( Storage storage self, address operator ) public { self.operatorLocks[operator].releaseLock(msg.sender); emit LockReleased(operator, msg.sender); } function releaseExpiredLock( Storage storage self, address operator, address operatorContract, address authorityVerifier ) public { LockUtils.LockSet storage locks = self.operatorLocks[operator]; require( locks.contains(operatorContract), "No matching lock present" ); bool expired = block.timestamp >= locks.getLockTime(operatorContract); bool disabled = !AuthorityVerifier(authorityVerifier) .isApprovedOperatorContract(operatorContract); require( expired || disabled, "Lock still active and valid" ); locks.releaseLock(operatorContract); emit ExpiredLockReleased(operator, operatorContract); } /// @dev AuthorityVerifier is a trusted implementation and not a third-party, /// external contract. AuthorityVerifier never reverts on the check and /// has a reasonable gas consumption. function isStakeLocked( Storage storage self, address operator, address authorityVerifier ) public view returns (bool) { LockUtils.Lock[] storage _locks = self.operatorLocks[operator].locks; LockUtils.Lock memory lock; for (uint i = 0; i < _locks.length; i++) { lock = _locks[i]; if (block.timestamp < lock.expiresAt) { if ( AuthorityVerifier(authorityVerifier) .isApprovedOperatorContract(lock.creator) ) { return true; } } } return false; } function isStakeReleased( Storage storage self, address operator, address operatorContract ) public view returns (bool) { LockUtils.LockSet storage locks = self.operatorLocks[operator]; // `getLockTime` returns 0 if the lock doesn't exist, // thus we don't need to check for its presence separately. return block.timestamp >= locks.getLockTime(operatorContract); } function getLocks( Storage storage self, address operator ) public view returns (address[] memory creators, uint256[] memory expirations) { uint256 lockCount = self.operatorLocks[operator].locks.length; creators = new address[](lockCount); expirations = new uint256[](lockCount); LockUtils.Lock memory lock; for (uint i = 0; i < lockCount; i++) { lock = self.operatorLocks[operator].locks[i]; creators[i] = lock.creator; expirations[i] = lock.expiresAt; } } } /** β–“β–“β–Œ β–“β–“ ▐▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–„ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œβ–β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–„β–„β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▄▄▄▄ β–“β–“β–“β–“β–“β–“β–„β–„β–„β–„ β–β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–€ ▐▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–Œ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–€β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓▀▀▀▀ β–“β–“β–“β–“β–“β–“β–€β–€β–€β–€ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ β–“β–“β–“β–“β–“β–“ β–€β–“β–“β–“β–“β–“β–“β–„ ▐▓▓▓▓▓▓ β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“ β–β–“β–“β–“β–“β–“β–Œ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“ Trust math, not hardware. */ pragma solidity 0.5.17; import "./KeepRegistry.sol"; /// @title AuthorityDelegator /// @notice An operator contract can delegate authority to other operator /// contracts by implementing the AuthorityDelegator interface. /// /// To delegate authority, /// the recipient of delegated authority must call `claimDelegatedAuthority`, /// specifying the contract it wants delegated authority from. /// The staking contract calls `delegator.__isRecognized(recipient)` /// and if the call returns `true`, /// the named delegator contract is set as the recipient's authority delegator. /// Any future checks of registry approval or per-operator authorization /// will transparently mirror the delegator's status. /// /// Authority can be delegated recursively; /// an operator contract receiving delegated authority /// can recognize other operator contracts as recipients of its authority. interface AuthorityDelegator { function __isRecognized(address delegatedAuthorityRecipient) external returns (bool); } /// @title AuthorityVerifier /// @notice An operator contract can delegate authority to other operator /// contracts. Entry in the registry is not updated and source contract remains /// listed there as authorized. This interface is a verifier that support verification /// of contract authorization in case of authority delegation from the source contract. interface AuthorityVerifier { /// @notice Returns true if the given operator contract has been approved /// for use. The function never reverts. function isApprovedOperatorContract(address _operatorContract) external view returns (bool); } contract Authorizations is AuthorityVerifier { // Authorized operator contracts. mapping(address => mapping (address => bool)) internal authorizations; // Granters of delegated authority to operator contracts. // E.g. keep factories granting delegated authority to keeps. // `delegatedAuthority[keep] = factory` mapping(address => address) internal delegatedAuthority; // Registry contract with a list of approved operator contracts and upgraders. KeepRegistry internal registry; modifier onlyApprovedOperatorContract(address operatorContract) { require( isApprovedOperatorContract(operatorContract), "Operator contract unapproved" ); _; } constructor(KeepRegistry _registry) public { registry = _registry; } /// @notice Gets the authorizer for the specified operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address); /// @notice Authorizes operator contract to access staked token balance of /// the provided operator. Can only be executed by stake operator authorizer. /// Contracts using delegated authority /// cannot be authorized with `authorizeOperatorContract`. /// Instead, authorize `getAuthoritySource(_operatorContract)`. /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. function authorizeOperatorContract(address _operator, address _operatorContract) public onlyApprovedOperatorContract(_operatorContract) { require( authorizerOf(_operator) == msg.sender, "Not operator authorizer" ); require( getAuthoritySource(_operatorContract) == _operatorContract, "Delegated authority used" ); authorizations[_operatorContract][_operator] = true; } /// @notice Checks if operator contract has access to the staked token balance of /// the provided operator. /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool) { return authorizations[getAuthoritySource(_operatorContract)][_operator]; } /// @notice Grant the sender the same authority as `delegatedAuthoritySource` /// @dev If `delegatedAuthoritySource` is an approved operator contract /// and recognizes the claimant, this relationship will be recorded in /// `delegatedAuthority`. Later, the claimant can slash, seize, place locks etc. /// on operators that have authorized the `delegatedAuthoritySource`. /// If the `delegatedAuthoritySource` is disabled with the panic button, /// any recipients of delegated authority from it will also be disabled. function claimDelegatedAuthority( address delegatedAuthoritySource ) public onlyApprovedOperatorContract(delegatedAuthoritySource) { require( AuthorityDelegator(delegatedAuthoritySource).__isRecognized(msg.sender), "Unrecognized claimant" ); delegatedAuthority[msg.sender] = delegatedAuthoritySource; } /// @notice Checks if the operator contract is authorized in the registry. /// If the contract uses delegated authority it checks authorization of the /// source contract. /// @param _operatorContract address of operator contract. /// @return True if operator contract is approved, false if operator contract /// has not been approved or if it was disabled by the panic button. function isApprovedOperatorContract(address _operatorContract) public view returns (bool) { return registry.isApprovedOperatorContract( getAuthoritySource(_operatorContract) ); } /// @notice Get the source of the operator contract's authority. /// If the contract uses delegated authority, /// returns the original source of the delegated authority. /// If the contract doesn't use delegated authority, /// returns the contract itself. /// Authorize `getAuthoritySource(operatorContract)` /// to grant `operatorContract` the authority to penalize an operator. function getAuthoritySource( address operatorContract ) public view returns (address) { address delegatedAuthoritySource = delegatedAuthority[operatorContract]; if (delegatedAuthoritySource == address(0)) { return operatorContract; } return getAuthoritySource(delegatedAuthoritySource); } } pragma solidity 0.5.17; library LockUtils { struct Lock { address creator; uint96 expiresAt; } /// @notice The LockSet is like an array of unique `uint256`s, /// but additionally supports O(1) membership tests and removals. /// @dev Because the LockSet relies on a mapping, /// it can only be used in storage, not in memory. struct LockSet { // locks[positions[lock.creator] - 1] = lock Lock[] locks; mapping(address => uint256) positions; } /// @notice Check whether the LockSet `self` contains a lock by `creator` function contains(LockSet storage self, address creator) internal view returns (bool) { return (self.positions[creator] != 0); } function getLockTime(LockSet storage self, address creator) internal view returns (uint96) { uint256 positionPlusOne = self.positions[creator]; if (positionPlusOne == 0) { return 0; } return self.locks[positionPlusOne - 1].expiresAt; } /// @notice Set the lock of `creator` to `expiresAt`, /// overriding the current value if any. function setLock( LockSet storage self, address _creator, uint96 _expiresAt ) internal { uint256 positionPlusOne = self.positions[_creator]; Lock memory lock = Lock(_creator, _expiresAt); // No existing lock if (positionPlusOne == 0) { self.locks.push(lock); self.positions[_creator] = self.locks.length; // Existing lock present } else { self.locks[positionPlusOne - 1].expiresAt = _expiresAt; } } /// @notice Remove the lock of `creator`. /// If no lock present, do nothing. function releaseLock( LockSet storage self, address _creator ) internal { uint256 positionPlusOne = self.positions[_creator]; if (positionPlusOne != 0) { uint256 lockCount = self.locks.length; if (positionPlusOne != lockCount) { // Not the last lock, // so we need to move the last lock into the emptied position. Lock memory lastLock = self.locks[lockCount - 1]; self.locks[positionPlusOne - 1] = lastLock; self.positions[lastLock.creator] = positionPlusOne; } self.locks.length--; self.positions[_creator] = 0; } } /// @notice Return the locks of the LockSet `self`. function enumerate(LockSet storage self) internal view returns (Lock[] memory) { return self.locks; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../TokenStakingEscrow.sol"; import "../../utils/OperatorParams.sol"; /// @notice TokenStaking contract library allowing to perform two-step stake /// top-ups for existing delegations. /// Top-up is a two-step process: it is initiated with a declared top-up value /// and after waiting for at least the initialization period it can be /// committed. library TopUps { using SafeMath for uint256; using OperatorParams for uint256; event TopUpInitiated(address indexed operator, uint256 topUp); event TopUpCompleted(address indexed operator, uint256 newAmount); struct TopUp { uint256 amount; uint256 createdAt; } struct Storage { // operator -> TopUp mapping(address => TopUp) topUps; } /// @notice Performs top-up in one step when stake is not yet initialized by /// adding the top-up amount to the stake and resetting stake initialization /// time counter. /// @dev This function should be called only for not yet initialized stake. /// @param value Top-up value, the number of tokens added to the stake. /// @param operator Operator The operator with existing delegation to which /// the tokens should be added to. /// @param operatorParams Parameters of that operator, as stored in the /// staking contract. /// @param escrow Reference to TokenStakingEscrow contract. /// @return New value of parameters. It should be updated for the operator /// in the staking contract. function instantComplete( Storage storage self, uint256 value, address operator, uint256 operatorParams, TokenStakingEscrow escrow ) public returns (uint256 newParams) { // Stake is not yet initialized so we don't need to check if the // operator is not undelegating - initializing and undelegating at the // same time is not possible. We do however, need to check whether the // operator has not canceled its previous stake for that operator, // depositing the stake it in the escrow. We do not want to allow // resurrecting operators with cancelled stake by top-ups. require( !escrow.hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); require(value > 0, "Top-up value must be greater than zero"); uint256 newAmount = operatorParams.getAmount().add(value); newParams = operatorParams.setAmountAndCreationTimestamp( newAmount, block.timestamp ); emit TopUpCompleted(operator, newAmount); } /// @notice Initiates top-up of the given value for tokens delegated to /// the provided operator. If there is an existing top-up still /// initializing, top-up values are summed up and initialization period /// is set to the current block timestamp. /// @dev This function should be called only for active operators with /// initialized stake. /// @param value Top-up value, the number of tokens added to the stake. /// @param operator Operator The operator with existing delegation to which /// the tokens should be added to. /// @param operatorParams Parameters of that operator, as stored in the /// staking contract. /// @param escrow Reference to TokenStakingEscrow contract. function initiate( Storage storage self, uint256 value, address operator, uint256 operatorParams, TokenStakingEscrow escrow ) public { // Stake is initialized, the operator is still active so we need // to check if it's not undelegating. require(!isUndelegating(operatorParams), "Stake undelegated"); // We also need to check if the stake for the operator is not already // in the escrow because it's been previously cancelled. require( !escrow.hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); require(value > 0, "Top-up value must be greater than zero"); TopUp memory awaiting = self.topUps[operator]; self.topUps[operator] = TopUp(awaiting.amount.add(value), now); emit TopUpInitiated(operator, value); } /// @notice Commits the top-up if it passed the initialization period. /// Tokens are added to the stake once the top-up is committed. /// @param operator Operator The operator with a pending stake top-up. /// @param initializationPeriod Stake initialization period. function commit( Storage storage self, address operator, uint256 operatorParams, uint256 initializationPeriod ) public returns (uint256 newParams) { TopUp memory topUp = self.topUps[operator]; require(topUp.amount > 0, "No top up to commit"); require( now > topUp.createdAt.add(initializationPeriod), "Stake is initializing" ); uint256 newAmount = operatorParams.getAmount().add(topUp.amount); newParams = operatorParams.setAmount(newAmount); delete self.topUps[operator]; emit TopUpCompleted(operator, newAmount); } /// @notice Cancels pending, initiating top-up. If there is no initiating /// top-up for the operator, function does nothing. This function should be /// used when the stake is recovered to return tokens from a pending, /// initiating top-up. /// @param operator Operator The operator from which the stake is recovered. function cancel( Storage storage self, address operator ) public returns (uint256) { TopUp memory topUp = self.topUps[operator]; if (topUp.amount == 0) { return 0; } delete self.topUps[operator]; return topUp.amount; } /// @notice Returns true if the given operatorParams indicate that the /// operator is undelegating its stake or that it completed stake /// undelegation. /// @param operatorParams Parameters of the operator, as stored in the /// staking contract. function isUndelegating(uint256 operatorParams) internal view returns (bool) { uint256 undelegatedAt = operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt); } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library PercentUtils { using SafeMath for uint256; // Return `b`% of `a` // 200.percent(40) == 80 // Commutative, works both ways function percent(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(100); } // Return `a` as percentage of `b`: // 80.asPercentOf(200) == 40 function asPercentOf(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(100).div(b); } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./TokenStaking.sol"; import "./TokenSender.sol"; import "./utils/BytesLib.sol"; /// @dev Interface of sender contract for approveAndCall pattern. interface tokenSender { function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external; } contract TokenGrantStake { using SafeMath for uint256; using BytesLib for bytes; ERC20Burnable token; TokenStaking tokenStaking; address tokenGrant; // Address of the master grant contract. uint256 grantId; // ID of the grant for this stake. uint256 amount; // Amount of staked tokens. address operator; // Operator of the stake. constructor( address _tokenAddress, uint256 _grantId, address _tokenStaking ) public { require( _tokenAddress != address(0x0), "Token address can't be zero." ); require( _tokenStaking != address(0x0), "Staking contract address can't be zero." ); token = ERC20Burnable(_tokenAddress); tokenGrant = msg.sender; grantId = _grantId; tokenStaking = TokenStaking(_tokenStaking); } function stake( uint256 _amount, bytes memory _extraData ) public onlyGrant { amount = _amount; operator = _extraData.toAddress(20); tokenSender(address(token)).approveAndCall( address(tokenStaking), _amount, _extraData ); } function getGrantId() public view onlyGrant returns (uint256) { return grantId; } function getAmount() public view onlyGrant returns (uint256) { return amount; } function getStakingContract() public view onlyGrant returns (address) { return address(tokenStaking); } function getDetails() public view onlyGrant returns ( uint256 _grantId, uint256 _amount, address _tokenStaking ) { return ( grantId, amount, address(tokenStaking) ); } function cancelStake() public onlyGrant returns (uint256) { tokenStaking.cancelStake(operator); return returnTokens(); } function undelegate() public onlyGrant { tokenStaking.undelegate(operator); } function recoverStake() public onlyGrant returns (uint256) { tokenStaking.recoverStake(operator); return returnTokens(); } function returnTokens() internal returns (uint256) { uint256 returnedAmount = token.balanceOf(address(this)); amount -= returnedAmount; token.transfer(tokenGrant, returnedAmount); return returnedAmount; } modifier onlyGrant { require( msg.sender == tokenGrant, "For token grant contract only" ); _; } } pragma solidity 0.5.17; /// @title GrantStakingPolicy /// @notice A staking policy defines the function `getStakeableAmount` /// which calculates how many tokens may be staked from a token grant. contract GrantStakingPolicy { function getStakeableAmount( uint256 _now, uint256 grantedAmount, uint256 duration, uint256 start, uint256 cliff, uint256 withdrawn) public view returns (uint256); } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library UnlockingSchedule { using SafeMath for uint256; function getUnlockedAmount( uint256 _now, uint256 grantedAmount, uint256 duration, uint256 start, uint256 cliff ) internal pure returns (uint256) { bool cliffNotReached = _now < cliff; if (cliffNotReached) { return 0; } uint256 timeElapsed = _now.sub(start); bool unlockingPeriodFinished = timeElapsed >= duration; if (unlockingPeriodFinished) { return grantedAmount; } return grantedAmount.mul(timeElapsed).div(duration); } } pragma solidity 0.5.17; /* Verison pulled from https://github.com/summa-tx/bitcoin-spv/blob/2535e4edaeaac4b2b095903fce684ae1c05761bc/solidity/contracts/BytesLib.sol */ /* 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) { 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 toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1), "Uint8 conversion out of bounds."); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } 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.17; /// @title KeepRegistry /// @notice Governance owned registry of approved contracts and roles. contract KeepRegistry { enum ContractStatus {New, Approved, Disabled} // Governance role is to enable recovery from key compromise by rekeying // other roles. Also, it can disable operator contract panic buttons // permanently. address public governance; // Registry Keeper maintains approved operator contracts. Each operator // contract must be approved before it can be authorized by a staker or // used by a service contract. address public registryKeeper; // Each operator contract has a Panic Button which can disable malicious // or malfunctioning contract that have been previously approved by the // Registry Keeper. // // New operator contract added to the registry has a default panic button // value assigned (defaultPanicButton). Panic button for each operator // contract can be later updated by Governance to individual value. // // It is possible to disable panic button for individual contract by // setting the panic button to zero address. In such case, operator contract // can not be disabled and is permanently approved in the registry. mapping(address => address) public panicButtons; // Default panic button for each new operator contract added to the // registry. Can be later updated for each contract. address public defaultPanicButton; // Each service contract has a Operator Contract Upgrader whose purpose // is to manage operator contracts for that specific service contract. // The Operator Contract Upgrader can add new operator contracts to the // service contract’s operator contract list, and deprecate old ones. mapping(address => address) public operatorContractUpgraders; // Operator contract may have a Service Contract Upgrader whose purpose is // to manage service contracts for that specific operator contract. // Service Contract Upgrader can add and remove service contracts // from the list of service contracts approved to work with the operator // contract. List of service contracts is maintained in the operator // contract and is optional - not every operator contract needs to have // a list of service contracts it wants to cooperate with. mapping(address => address) public serviceContractUpgraders; // The registry of operator contracts mapping(address => ContractStatus) public operatorContracts; event OperatorContractApproved(address operatorContract); event OperatorContractDisabled(address operatorContract); event GovernanceUpdated(address governance); event RegistryKeeperUpdated(address registryKeeper); event DefaultPanicButtonUpdated(address defaultPanicButton); event OperatorContractPanicButtonDisabled(address operatorContract); event OperatorContractPanicButtonUpdated( address operatorContract, address panicButton ); event OperatorContractUpgraderUpdated( address serviceContract, address upgrader ); event ServiceContractUpgraderUpdated( address operatorContract, address keeper ); modifier onlyGovernance() { require(governance == msg.sender, "Not authorized"); _; } modifier onlyRegistryKeeper() { require(registryKeeper == msg.sender, "Not authorized"); _; } modifier onlyPanicButton(address _operatorContract) { address panicButton = panicButtons[_operatorContract]; require(panicButton != address(0), "Panic button disabled"); require(panicButton == msg.sender, "Not authorized"); _; } modifier onlyForNewContract(address _operatorContract) { require( isNewOperatorContract(_operatorContract), "Not a new operator contract" ); _; } modifier onlyForApprovedContract(address _operatorContract) { require( isApprovedOperatorContract(_operatorContract), "Not an approved operator contract" ); _; } constructor() public { governance = msg.sender; registryKeeper = msg.sender; defaultPanicButton = msg.sender; } function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceUpdated(governance); } function setRegistryKeeper(address _registryKeeper) public onlyGovernance { registryKeeper = _registryKeeper; emit RegistryKeeperUpdated(registryKeeper); } function setDefaultPanicButton(address _panicButton) public onlyGovernance { defaultPanicButton = _panicButton; emit DefaultPanicButtonUpdated(defaultPanicButton); } function setOperatorContractPanicButton( address _operatorContract, address _panicButton ) public onlyForApprovedContract(_operatorContract) onlyGovernance { require( panicButtons[_operatorContract] != address(0), "Disabled panic button cannot be updated" ); require( _panicButton != address(0), "Panic button must be non-zero address" ); panicButtons[_operatorContract] = _panicButton; emit OperatorContractPanicButtonUpdated( _operatorContract, _panicButton ); } function disableOperatorContractPanicButton(address _operatorContract) public onlyForApprovedContract(_operatorContract) onlyGovernance { require( panicButtons[_operatorContract] != address(0), "Panic button already disabled" ); panicButtons[_operatorContract] = address(0); emit OperatorContractPanicButtonDisabled(_operatorContract); } function setOperatorContractUpgrader( address _serviceContract, address _operatorContractUpgrader ) public onlyGovernance { operatorContractUpgraders[_serviceContract] = _operatorContractUpgrader; emit OperatorContractUpgraderUpdated( _serviceContract, _operatorContractUpgrader ); } function setServiceContractUpgrader( address _operatorContract, address _serviceContractUpgrader ) public onlyGovernance { serviceContractUpgraders[_operatorContract] = _serviceContractUpgrader; emit ServiceContractUpgraderUpdated( _operatorContract, _serviceContractUpgrader ); } function approveOperatorContract(address operatorContract) public onlyForNewContract(operatorContract) onlyRegistryKeeper { operatorContracts[operatorContract] = ContractStatus.Approved; panicButtons[operatorContract] = defaultPanicButton; emit OperatorContractApproved(operatorContract); } function disableOperatorContract(address operatorContract) public onlyForApprovedContract(operatorContract) onlyPanicButton(operatorContract) { operatorContracts[operatorContract] = ContractStatus.Disabled; emit OperatorContractDisabled(operatorContract); } function isNewOperatorContract(address operatorContract) public view returns (bool) { return operatorContracts[operatorContract] == ContractStatus.New; } function isApprovedOperatorContract(address operatorContract) public view returns (bool) { return operatorContracts[operatorContract] == ContractStatus.Approved; } function operatorContractUpgraderFor(address _serviceContract) public view returns (address) { return operatorContractUpgraders[_serviceContract]; } function serviceContractUpgraderFor(address _operatorContract) public view returns (address) { return serviceContractUpgraders[_operatorContract]; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/grant/UnlockingSchedule.sol"; import "./utils/BytesLib.sol"; import "./utils/AddressArrayUtils.sol"; import "./TokenStaking.sol"; import "./TokenGrantStake.sol"; import "./GrantStakingPolicy.sol"; /// @title TokenGrant /// @notice A token grant contract for a specified standard ERC20Burnable token. /// Has additional functionality to stake delegate/undelegate token grants. /// Tokens are granted to the grantee via unlocking scheme and can be /// withdrawn gradually based on the unlocking schedule cliff and unlocking duration. /// Optionally grant can be revoked by the token grant manager. contract TokenGrant { using SafeMath for uint256; using UnlockingSchedule for uint256; using SafeERC20 for ERC20Burnable; using BytesLib for bytes; using AddressArrayUtils for address[]; event TokenGrantCreated(uint256 id); event TokenGrantWithdrawn(uint256 indexed grantId, uint256 amount); event TokenGrantStaked(uint256 indexed grantId, uint256 amount, address operator); event TokenGrantRevoked(uint256 id); event StakingContractAuthorized(address indexed grantManager, address stakingContract); struct Grant { address grantManager; // Token grant manager. address grantee; // Address to which granted tokens are going to be withdrawn. uint256 revokedAt; // Timestamp at which grant was revoked by the grant manager. uint256 revokedAmount; // The number of tokens revoked from the grantee. uint256 revokedWithdrawn; // The number of tokens returned to the grant creator. bool revocable; // Whether grant manager can revoke the grant. uint256 amount; // Amount of tokens to be granted. uint256 duration; // Duration in seconds of the period in which the granted tokens will unlock. uint256 start; // Timestamp at which the linear unlocking schedule will start. uint256 cliff; // Timestamp before which no tokens will be unlocked. uint256 withdrawn; // Amount that was withdrawn to the grantee. uint256 staked; // Amount that was staked by the grantee. GrantStakingPolicy stakingPolicy; } uint256 public numGrants; ERC20Burnable public token; // Staking contracts authorized by the given grant manager. // grant manager -> staking contract -> authorized? mapping(address => mapping (address => bool)) internal stakingContracts; // Token grants. mapping(uint256 => Grant) public grants; // Token grants stakes. mapping(address => TokenGrantStake) public grantStakes; // Mapping of token grant IDs per particular address // involved in a grant as a grantee or as a grant manager. mapping(address => uint256[]) public grantIndices; // Token grants balances. Sum of all granted tokens to a grantee. // This includes granted tokens that are already unlocked and // available to be withdrawn to the grantee mapping(address => uint256) public balances; // Mapping of operator addresses per particular grantee address. mapping(address => address[]) public granteesToOperators; /// @notice Creates a token grant contract for a provided Standard ERC20Burnable token. /// @param _tokenAddress address of a token that will be linked to this contract. constructor(address _tokenAddress) public { require(_tokenAddress != address(0x0), "Token address can't be zero."); token = ERC20Burnable(_tokenAddress); } /// @notice Used by grant manager to authorize staking contract with the given /// address. function authorizeStakingContract(address _stakingContract) public { require( _stakingContract != address(0x0), "Staking contract address can't be zero" ); stakingContracts[msg.sender][_stakingContract] = true; emit StakingContractAuthorized(msg.sender, _stakingContract); } /// @notice Gets the amount of granted tokens to the specified address. /// @param _owner The address to query the grants balance of. /// @return An uint256 representing the grants balance owned by the passed address. function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /// @notice Gets the stake balance of the specified address. /// @param _address The address to query the balance of. /// @return An uint256 representing the amount staked by the passed address. function stakeBalanceOf(address _address) public view returns (uint256 balance) { for (uint i = 0; i < grantIndices[_address].length; i++) { uint256 id = grantIndices[_address][i]; balance += grants[id].staked; } return balance; } /// @notice Gets grant by ID. Returns only basic grant data. /// If you need unlocking schedule for the grant you must call `getGrantUnlockingSchedule()` /// This is to avoid Ethereum `Stack too deep` issue described here: /// https://forum.ethereum.org/discussion/2400/error-stack-too-deep-try-removing-local-variables /// @param _id ID of the token grant. /// @return amount The amount of tokens the grant provides. /// @return withdrawn The amount of tokens that have already been withdrawn /// from the grant. /// @return staked The amount of tokens that have been staked from the grant. /// @return revoked A boolean indicating whether the grant has been revoked, /// which is to say that it is no longer unlocking. /// @return grantee The grantee of grant. function getGrant(uint256 _id) public view returns ( uint256 amount, uint256 withdrawn, uint256 staked, uint256 revokedAmount, uint256 revokedAt, address grantee ) { return ( grants[_id].amount, grants[_id].withdrawn, grants[_id].staked, grants[_id].revokedAmount, grants[_id].revokedAt, grants[_id].grantee ); } /// @notice Gets grant unlocking schedule by grant ID. /// @param _id ID of the token grant. /// @return grantManager The address designated as the manager of the grant, /// which is the only address that can revoke this grant. /// @return duration The duration, in seconds, during which the tokens will /// unlocking linearly. /// @return start The start time, as a timestamp comparing to `now`. /// @return cliff The timestamp, before which none of the tokens in the grant /// will be unlocked, and after which a linear amount based on /// the time elapsed since the start will be unlocked. /// @return policy The address of the grant's staking policy. function getGrantUnlockingSchedule( uint256 _id ) public view returns ( address grantManager, uint256 duration, uint256 start, uint256 cliff, address policy ) { return ( grants[_id].grantManager, grants[_id].duration, grants[_id].start, grants[_id].cliff, address(grants[_id].stakingPolicy) ); } /// @notice Gets grant ids of the specified address. /// @param _granteeOrGrantManager The address to query. /// @return An uint256 array of grant IDs. function getGrants(address _granteeOrGrantManager) public view returns (uint256[] memory) { return grantIndices[_granteeOrGrantManager]; } /// @notice Gets operator addresses of the specified grantee address. /// @param grantee The grantee address. /// @return An array of all operators for a given grantee. function getGranteeOperators(address grantee) public view returns (address[] memory) { return granteesToOperators[grantee]; } /// @notice Gets grant stake details of the given operator. /// @param operator The operator address. /// @return grantId ID of the token grant. /// @return amount The amount of tokens the given operator delegated. /// @return stakingContract The address of staking contract. function getGrantStakeDetails(address operator) public view returns (uint256 grantId, uint256 amount, address stakingContract) { return grantStakes[operator].getDetails(); } /// @notice Receives approval of token transfer and creates a token grant with a unlocking /// schedule where balance withdrawn to the grantee gradually in a linear fashion until /// start + duration. By then all of the balance will have unlocked. /// @param _from The owner of the tokens who approved them to transfer. /// @param _amount Approved amount for the transfer to create token grant. /// @param _token Token contract address. /// @param _extraData This byte array must have the following values ABI encoded: /// grantManager (address) Address of the grant manager. /// grantee (address) Address of the grantee. /// duration (uint256) Duration in seconds of the unlocking period. /// start (uint256) Timestamp at which unlocking will start. /// cliffDuration (uint256) Duration in seconds of the cliff; /// no tokens will be unlocked until the time `start + cliff`. /// revocable (bool) Whether the token grant is revocable or not (1 or 0). /// stakingPolicy (address) Address of the staking policy for the grant. function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _extraData) public { require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract."); require(_amount <= token.balanceOf(_from), "Sender must have enough amount."); (address _grantManager, address _grantee, uint256 _duration, uint256 _start, uint256 _cliffDuration, bool _revocable, address _stakingPolicy) = abi.decode( _extraData, (address, address, uint256, uint256, uint256, bool, address) ); require(_grantee != address(0), "Grantee address can't be zero."); require( _cliffDuration <= _duration, "Unlocking cliff duration must be less or equal total unlocking duration." ); require(_stakingPolicy != address(0), "Staking policy can't be zero."); uint256 id = numGrants++; grants[id] = Grant( _grantManager, _grantee, 0, 0, 0, _revocable, _amount, _duration, _start, _start.add(_cliffDuration), 0, 0, GrantStakingPolicy(_stakingPolicy) ); // Maintain a record to make it easier to query grants by grant manager. grantIndices[_from].push(id); // Maintain a record to make it easier to query grants by grantee. grantIndices[_grantee].push(id); token.safeTransferFrom(_from, address(this), _amount); // Maintain a record of the unlocked amount balances[_grantee] = balances[_grantee].add(_amount); emit TokenGrantCreated(id); } /// @notice Withdraws Token grant amount to grantee. /// @dev Transfers unlocked tokens of the token grant to grantee. /// @param _id Grant ID. function withdraw(uint256 _id) public { uint256 amount = withdrawable(_id); require(amount > 0, "Grant available to withdraw amount should be greater than zero."); // Update withdrawn amount. grants[_id].withdrawn = grants[_id].withdrawn.add(amount); // Update grantee grants balance. balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(amount); // Transfer tokens from this contract balance to the grantee token balance. token.safeTransfer(grants[_id].grantee, amount); emit TokenGrantWithdrawn(_id, amount); } /// @notice Calculates and returns unlocked grant amount. /// @dev Calculates token grant amount that has already unlocked, /// including any tokens that have already been withdrawn by the grantee as well /// as any tokens that are available to withdraw but have not yet been withdrawn. /// @param _id Grant ID. function unlockedAmount(uint256 _id) public view returns (uint256) { Grant storage grant = grants[_id]; return (grant.revokedAt != 0) // Grant revoked -> return what is remaining ? grant.amount.sub(grant.revokedAmount) // Not revoked -> calculate the unlocked amount normally : now.getUnlockedAmount( grant.amount, grant.duration, grant.start, grant.cliff ); } /// @notice Calculates withdrawable granted amount. /// @dev Calculates the amount that has already unlocked but hasn't been withdrawn yet. /// @param _id Grant ID. function withdrawable(uint256 _id) public view returns (uint256) { uint256 unlocked = unlockedAmount(_id); uint256 withdrawn = grants[_id].withdrawn; uint256 staked = grants[_id].staked; if (withdrawn.add(staked) >= unlocked) { return 0; } else { return unlocked.sub(withdrawn).sub(staked); } } /// @notice Allows the grant manager to revoke the grant. /// @dev Granted tokens that are already unlocked (releasable amount) /// remain in the grant so grantee can still withdraw them /// the rest are revoked and withdrawable by token grant manager. /// @param _id Grant ID. function revoke(uint256 _id) public { require(grants[_id].grantManager == msg.sender, "Only grant manager can revoke."); require(grants[_id].revocable, "Grant must be revocable in the first place."); require(grants[_id].revokedAt == 0, "Grant must not be already revoked."); uint256 unlockedAmount = unlockedAmount(_id); uint256 revokedAmount = grants[_id].amount.sub(unlockedAmount); grants[_id].revokedAt = now; grants[_id].revokedAmount = revokedAmount; // Update grantee's grants balance. balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(revokedAmount); emit TokenGrantRevoked(_id); } /// @notice Allows the grant manager to withdraw revoked tokens. /// @dev Will withdraw as many of the revoked tokens as possible /// without pushing the grant contract into a token deficit. /// If the grantee has staked more tokens than the unlocked amount, /// those tokens will remain in the grant until undelegated and returned, /// after which they can be withdrawn by calling `withdrawRevoked` again. /// @param _id Grant ID. function withdrawRevoked(uint256 _id) public { Grant storage grant = grants[_id]; require( grant.grantManager == msg.sender, "Only grant manager can withdraw revoked tokens." ); uint256 revoked = grant.revokedAmount; uint256 revokedWithdrawn = grant.revokedWithdrawn; require(revokedWithdrawn < revoked, "All revoked tokens withdrawn."); uint256 revokedRemaining = revoked.sub(revokedWithdrawn); uint256 totalAmount = grant.amount; uint256 staked = grant.staked; uint256 granteeWithdrawn = grant.withdrawn; uint256 remainingPresentInGrant = totalAmount.sub(staked).sub(revokedWithdrawn).sub(granteeWithdrawn); require(remainingPresentInGrant > 0, "No revoked tokens withdrawable."); uint256 amountToWithdraw = remainingPresentInGrant < revokedRemaining ? remainingPresentInGrant : revokedRemaining; token.safeTransfer(msg.sender, amountToWithdraw); grant.revokedWithdrawn += amountToWithdraw; } /// @notice Stake token grant. /// @dev Stakable token grant amount is determined /// by the grant's staking policy. /// @param _id Grant Id. /// @param _stakingContract Address of the staking contract. /// @param _amount Amount to stake. /// @param _extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes) /// - Operator address (20 bytes) /// - Authorizer address (20 bytes) function stake(uint256 _id, address _stakingContract, uint256 _amount, bytes memory _extraData) public { require(grants[_id].grantee == msg.sender, "Only grantee of the grant can stake it."); require(grants[_id].revokedAt == 0, "Revoked grant can not be staked"); require( stakingContracts[grants[_id].grantManager][_stakingContract], "Provided staking contract is not authorized." ); // Expecting 60 bytes _extraData for stake delegation. require(_extraData.length == 60, "Stake delegation data must be provided."); address operator = _extraData.toAddress(20); // Calculate available amount. Amount of unlocked tokens minus what user already withdrawn and staked. require(_amount <= availableToStake(_id), "Must have available granted amount to stake."); // Keep staking record. TokenGrantStake grantStake = new TokenGrantStake( address(token), _id, _stakingContract ); grantStakes[operator] = grantStake; granteesToOperators[grants[_id].grantee].push(operator); grants[_id].staked += _amount; token.transfer(address(grantStake), _amount); // Staking contract expects 40 bytes _extraData for stake delegation. // 20 bytes beneficiary's address + 20 bytes operator's address. grantStake.stake(_amount, _extraData); emit TokenGrantStaked(_id, _amount, operator); } /// @notice Returns the amount of tokens available for staking from the grant. /// The stakeable amount is determined by the staking policy of the grant. /// If the grantee has withdrawn some tokens /// or the policy returns an erroneously high value, /// the stakeable amount is limited to the number of tokens remaining. /// @param _grantId Identifier of the grant function availableToStake(uint256 _grantId) public view returns (uint256) { Grant storage grant = grants[_grantId]; // Revoked grants cannot be staked. // If the grant isn't revoked, the number of revoked tokens is 0. if (grant.revokedAt != 0) { return 0; } uint256 amount = grant.amount; uint256 withdrawn = grant.withdrawn; uint256 remaining = amount.sub(withdrawn); uint256 stakeable = grant.stakingPolicy.getStakeableAmount( now, amount, grant.duration, grant.start, grant.cliff, withdrawn ); // Clamp the stakeable amount to what is left in the grant // in the case of a malfunctioning staking policy. if (stakeable > remaining) { stakeable = remaining; } return stakeable.sub(grant.staked); } /// @notice Cancels delegation within the operator initialization period /// without being subjected to the stake lockup for the undelegation period. /// This can be used to undo mistaken delegation to the wrong operator address. /// @param _operator Address of the stake operator. function cancelStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( msg.sender == _operator || msg.sender == grants[grantId].grantee, "Only operator or grantee can cancel the delegation." ); uint256 returned = grantStake.cancelStake(); grants[grantId].staked = grants[grantId].staked.sub(returned); } /// @notice Undelegate the token grant. /// @param _operator Operator of the stake. function undelegate(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( msg.sender == _operator || msg.sender == grants[grantId].grantee, "Only operator or grantee can undelegate." ); grantStake.undelegate(); } /// @notice Force cancellation of a revoked grant's stake. /// Can be used by the grant manager /// to immediately withdraw tokens back into the grant, /// from an operator still within the initialization period. /// These tokens can then be withdrawn /// if some revoked tokens haven't been withdrawn yet. function cancelRevokedStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( grants[grantId].revokedAt != 0, "Grant must be revoked" ); require( msg.sender == grants[grantId].grantManager, "Only grant manager can force cancellation of revoked grant stake." ); uint256 returned = grantStake.cancelStake(); grants[grantId].staked = grants[grantId].staked.sub(returned); } /// @notice Force undelegation of a revoked grant's stake. /// @dev Can be called by the grant manager once the grant is revoked. /// Has to be done this way, instead of undelegating all operators when the /// grant is revoked, because the latter method is vulnerable to DoS via /// out-of-gas. function undelegateRevoked(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( grants[grantId].revokedAt != 0, "Grant must be revoked" ); require( msg.sender == grants[grantId].grantManager, "Only grant manager can force undelegation of revoked grant stake" ); grantStake.undelegate(); } /// @notice Recover stake of the token grant. /// Recovers the tokens correctly /// even if they were earlier recovered directly in the staking contract. /// @param _operator Operator of the stake. function recoverStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 returned = grantStake.recoverStake(); uint256 grantId = grantStake.getGrantId(); grants[grantId].staked = grants[grantId].staked.sub(returned); delete grantStakes[_operator]; } } pragma solidity 0.5.17; library AddressArrayUtils { function contains(address[] memory self, address _address) internal pure returns (bool) { for (uint i = 0; i < self.length; i++) { if (_address == self[i]) { return true; } } return false; } function removeAddress(address[] storage self, address _addressToRemove) internal returns (address[] storage) { for (uint i = 0; i < self.length; i++) { // If address is found in array. if (_addressToRemove == self[i]) { // Delete element at index and shift array. for (uint j = i; j < self.length-1; j++) { self[j] = self[j+1]; } self.length--; i--; } } return self; } }
Withdraws currently unlocked tokens deposited in the escrow after undelegating them from the provided operator. Only grantee or operator can call this function. This function works only for `ManagedGrant` grantees. For a standard grant, please use `withdraw` instead. operator Address of the operator from the undelegated/canceled delegation from which tokens were deposited.
function withdrawToManagedGrantee(address operator) public { Deposit memory deposit = deposits[operator]; address managedGrant = getGrantee(deposit.grantId); address grantee = getManagedGrantee(managedGrant); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); }
12,847,162
./partial_match/3/0xe5AAaA46c87Ba69C749f8F69fB0BAbd4a927D636/sources/TexMasterFarmer.sol
Update reward variables of the given pool to be up-to-date.For more simple, I lock reward for dev if mint reward in bonus time
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 TexForDev; uint256 TexForFarmer; (TexForDev, TexForFarmer) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint); if (TexForDev > 0) { Tex.mint(devaddr, TexForDev); if (block.number <= FINISH_BONUS_AT_BLOCK) { Tex.lock(devaddr, TexForDev.mul(PERCENT_LOCK_BONUS_REWARD).div(100)); } } Tex.mint(address(this), TexForFarmer); pool.accTexPerShare = pool.accTexPerShare.add(TexForFarmer.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
5,337,193
./partial_match/1/0x8fa702D65542596aC1AD3C5454C622C13e53085E/sources/Moona_Lisa_Print_Original.sol
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) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); }
2,771,305
./partial_match/1/0x9938108EB2aE01F1dFac94c603a26b1be106cDD7/sources/contracts/NestStaking.sol
exist bug must refresh WETH balance record after updating WETH balance or lastRewardsTotal could be less than the newest WETH balance in the next update
function withdrawSavingByGov(address ntoken, address to, uint256 amount) external nonReentrant onlyGovernance { require(flag == STAKING_FLAG_PAUSED, "Nest:Stak:!flag"); _pending_saving_amount[ntoken] = _pending_saving_amount[ntoken].sub(amount); uint256 _newTotal = rewardsTotal[ntoken].sub(amount); lastRewardsTotal[ntoken] = _newTotal; rewardsTotal[ntoken] = _newTotal; emit SavingWithdrawn(ntoken, to, amount); TransferHelper.safeTransferETH(to, amount); }
4,326,096
pragma solidity ^0.4.21; /** * Changes by https://www.docademic.com/ */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Destroyable is Ownable{ /** * @notice Allows to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner{ selfdestruct(owner); } } interface Token { function transfer(address _to, uint256 _value) external returns (bool); function balanceOf(address who) view external returns (uint256); } contract TokenVault is Ownable, Destroyable { using SafeMath for uint256; Token public token; /** * @dev Constructor. * @param _token The token address */ function TokenVault(address _token) public{ require(_token != address(0)); token = Token(_token); } /** * @dev Get the token balance of the contract. * @return _balance The token balance of this contract in wei */ function Balance() view public returns (uint256 _balance) { return token.balanceOf(address(this)); } /** * @dev Get the token balance of the contract. * @return _balance The token balance of this contract in ether */ function BalanceEth() view public returns (uint256 _balance) { return token.balanceOf(address(this)) / 1 ether; } /** * @dev Allows the owner to flush the tokens of the contract. */ function transferTokens(address _to, uint256 amount) public onlyOwner { token.transfer(_to, amount); } /** * @dev Allows the owner to flush the tokens of the contract. */ function flushTokens() public onlyOwner { token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Allows the owner to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner { token.transfer(owner, token.balanceOf(address(this))); selfdestruct(owner); } }
Get the token balance of the contract. return _balance The token balance of this contract in ether/
function BalanceEth() view public returns (uint256 _balance) { return token.balanceOf(address(this)) / 1 ether; }
13,424,472
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.0; interface ILendingPoolAddressesProviderV2 { /** * @notice Get the current address for Aave LendingPool * @dev Lending pool is the core contract on which to call deposit */ function getLendingPool() external view returns (address); } interface IAaveATokenV2 { /** * @notice returns the current total aToken balance of _user all interest collected included. * To obtain the user asset principal balance with interests excluded , ERC20 non-standard * method principalBalanceOf() can be used. */ function balanceOf(address _user) external view returns(uint256); } interface IAaveLendingPoolV2 { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param reserve the address of the reserve * @param amount the amount to be deposited * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed * @param to address that will receive the underlying **/ function withdraw( address reserve, uint256 amount, address to ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } } } } 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"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } 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; } } abstract contract AbstractIntegration is IPlatformIntegration, ImmutableModule, ReentrancyGuard { event PTokenAdded(address indexed _bAsset, address _pToken); event Deposit(address indexed _bAsset, address _pToken, uint256 _amount); event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount); event PlatformWithdrawal(address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount); // mAsset has write access address public immutable mAssetAddress; // bAsset => pToken (Platform Specific Token Address) mapping(address => address) public override bAssetToPToken; // Full list of all bAssets supported here address[] internal bAssetsMapped; /** * @param _nexus Address of the Nexus * @param _mAsset Address of mAsset */ constructor( address _nexus, address _mAsset ) ReentrancyGuard() ImmutableModule(_nexus) { require(_mAsset != address(0), "Invalid mAsset address"); mAssetAddress = _mAsset; } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyMasset() { require(msg.sender == mAssetAddress, "Only the mAsset can execute"); _; } /*************************************** CONFIG ****************************************/ /** * @dev Provide support for bAsset by passing its pToken address. * This method can only be called by the system Governor * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _bAsset, address _pToken) external onlyGovernor { _setPTokenAddress(_bAsset, _pToken); } /** * @dev Provide support for bAsset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _bAsset, address _pToken) internal { require(bAssetToPToken[_bAsset] == address(0), "pToken already set"); require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses"); bAssetToPToken[_bAsset] = _pToken; bAssetsMapped.push(_bAsset); emit PTokenAdded(_bAsset, _pToken); _abstractSetPToken(_bAsset, _pToken); } function _abstractSetPToken(address _bAsset, address _pToken) internal virtual; /** * @dev Simple helper func to get the min of two values */ function _min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } // External // Libs /** * @title AaveV2Integration * @author Stability Labs Pty. Ltd. * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */ contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable basketManager; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _mAsset Address of mAsset * @param _platformAddress Generic platform address */ constructor( address _nexus, address _mAsset, address _platformAddress, address _basketManager ) AbstractIntegration(_nexus, _mAsset) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; basketManager = _basketManager; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); // Official checksummed AAVE token address // https://ethplorer.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 address aaveToken = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); MassetHelpers.safeInfiniteApprove(aaveToken, liquidator); emit RewardTokenApproved(address(aaveToken), liquidator); } /*************************************** CORE ****************************************/ /** * @dev Modifier to allow function calls only from the Governor. */ modifier massetOrManager() { require(msg.sender == mAssetAddress || msg.sender == basketManager, "Only mAsset or basketManager can execute"); _; } /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override massetOrManager nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if(_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyMasset nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyMasset nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if(_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyMasset nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken(address _bAsset, address /*_pToken*/) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
Withdraws _totalAmount from the lending pool, sending _amount to user / Send redeemed bAsset to the receiver
function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if(_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); }
626,326
pragma solidity ^0.4.20; contract POMDA { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "POMDA"; string public symbol = "POMDA"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function POMDA() public { } function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) //require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) // antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Calculate token sell value. It&39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code./ underflow attempts BTFO
function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; }
7,835,032
./full_match/11155111/0x26cA8F4556f2ACDd500F255898710E97Da67825d/sources/project_/contracts/verifier.sol
verify a ring signature, check balances of the provided value and mint an sbt if it is valid addresses the addresses of the ring (length must be even) (addresses = [key1-x, key1-y, key2-x, key2-y, ..., keyN-x, keyN-y]) tees the tees of the ring (length must be addresses.length/2) (tees = [tee1, tee2, ..., teeN]) seed the seed of the ring value the value to check -> balance of each address must be >= value message the message to verify the ring signature token the token we check the balance of addressesURI the URI of the addresses on IPFS verifierData is a string which could be used id the verifier wants to be sure that the sbt has been minted for him (example : his address or somethings he asked the prover to write)/ verify if the message is valid -> int(eth address of the msg.sender) == message verify the ring signature
function verify(uint256[] memory addresses, uint256[] memory tees, uint256 seed, uint256 value, uint256 message, address token, string memory addressesURI, string memory verifierData) public { require(addresses.length % 2 == 0 && tees.length == addresses.length / 2, "Invalid proof"); require(uint160(msg.sender) == message, "Invalid message"); for (uint i = 0; i < addresses.length; i+=2) { require(IERC20(token).balanceOf(pointToAddress([addresses[i],addresses[i+1]])) >= value, "Insufficient balance in at least one address"); } }
3,807,014
./full_match/11155111/0x12F8F4d80147922f59b57B8839fa7a9790902Db6/sources/project:/contracts/ERC721A.sol
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 memory _data ) public payable virtual override onlyAllowedOperator(from) { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } }
3,822,285
./full_match/1/0xaBCF57EB168f65841964fa410F48370c5AF057A5/sources/src/L1/BattleRoyaleL1.sol
Recovers assets from the contract (emergency use) It can be called by an authorized address assets Addresses of the assets to recover amounts Amounts of the assets to recover to Addresses to send the assets to/
function recoverAssets(address[] memory assets, uint256[] memory amounts, address[] memory to) external authorized { for (uint256 i = 0; i < assets.length; i++) { ERC20(assets[i]).transfer(to[i], amounts[i]); } }
17,168,398
./full_match/4/0x91B6Cf4f1018240dA60B7EFb93D65B0C6ea96242/sources/contracts/TT.sol
Updates the underlying token address
function setTokenAddress(address _tokenAddr) external onlyOwner { token = ERC20(_tokenAddr); }
12,431,059
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Cryptopaka.sol"; //******************************// // // // https://cryptopaka.com // // // //******************************// contract CryptopakaV2 is ERC721Enumerable, Ownable { string private _baseTokenURI = "https://api.cryptopaka.com/token/"; // if the contract is paused bool public paused = true; // if you can still adopt founder pakas bool public adoptable = true; // check if the given paka is part of the 6969 founder pakas mapping(uint256 => bool) public isFounder; // the token id of MoonCats that has been used mapping(uint256 => bool) public usedMoonCats; // the address of MoonCat owners that has claimed mapping(address => bool) public claimedOwners; // the number of pakas that can be claimed by MoonCat holders uint16 public moonCatGiftCount = 500; // Adoption fee of a single paka uint256 public constant price = .08 ether; // Contract of Cryptopaka V1 Cryptopaka private immutable v1Contract; // Contract of MoonCatAcclimator IERC721 private constant mca = IERC721(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69); // Search seed from Cryptopaka V1 used to prevent premining bytes32 public immutable searchSeed; // SHA-256 hash of the JavaScript parser bytes32 public immutable jsSHA256; constructor(address v1Address) ERC721("CryptopakaV2", "CPK") { Cryptopaka c = Cryptopaka(v1Address); v1Contract = c; searchSeed = c.searchSeed(); jsSHA256 = c.jsSHA256(); } /** * @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); /** * @dev Make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "paused"); _; } /** * @dev Make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "not paused"); _; } /** * @dev Triggers stopped state. */ function pause() public whenNotPaused onlyOwner { paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. */ function unpause() public whenPaused onlyOwner { paused = false; emit Unpaused(msg.sender); // v2 contract must own v1 contract require(v1Contract.owner() == address(this)); // v1 contract must be paused forever if (!v1Contract.paused()) { v1Contract.pause(); } } function setAdoptable(bool v) public onlyOwner { adoptable = v; } modifier canAdopt() { require(adoptable, "adoption has ended"); _; } /** * @dev See {ERC721-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory uri) public onlyOwner { _baseTokenURI = uri; } function _mintFounderSeed(address to, bytes32 seed) private { bytes32 h = keccak256(abi.encodePacked(seed, searchSeed)); require((h[30] | h[31] == 0x0) && uint8(h[29]) < 8, "invalid seed"); uint256 tokenId = uint256(h >> 216); // genesis paka are not adoptable require(!isGenesis(tokenId)); try v1Contract.ownerOf(tokenId) { revert("paka already adopted"); } catch { // paka not owned in v1, can mint safely isFounder[tokenId] = true; _mint(to, tokenId); } } function adopt(address to, bytes32 seed) public payable canAdopt { require(totalSupply() <= 6969 - 16); // exclude 16 genesis pakas require(price == msg.value, "incorrect ether value"); _mintFounderSeed(to, seed); } function claimWithMoonCat(uint256 tokenId, bytes32 seed) public canAdopt { require(totalSupply() <= 6969 - 16); // exclude 16 genesis pakas require(moonCatGiftCount > 0, "airdrop has ended"); require(mca.ownerOf(tokenId) == msg.sender, "not the owner"); require(!usedMoonCats[tokenId], "this MoonCat has already been used"); require(!claimedOwners[msg.sender], "you have already claimed"); usedMoonCats[tokenId] = true; claimedOwners[msg.sender] = true; --moonCatGiftCount; _mintFounderSeed(msg.sender, seed); } function migrate( address from, address to, uint256 tokenId ) public { require(v1Contract.ownerOf(tokenId) == from, "not the owner"); require(from == msg.sender || msg.sender == owner(), "not the owner"); isFounder[tokenId] = true; _mint(to, tokenId); } function mint(address to, uint256 tokenId) public onlyOwner { if (totalSupply() <= 6969) { isFounder[tokenId] = true; } _mint(to, tokenId); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function isGenesis(uint256 tokenId) public pure returns (bool) { return tokenId == 1099511562240 || tokenId == 1099511566336 || tokenId == 1099511570432 || tokenId == 1099511574528 || tokenId == 1099511578624 || tokenId == 1099511582720 || tokenId == 1099511586816 || tokenId == 1099511590912 || tokenId == 1099511595008 || tokenId == 1099511599104 || tokenId == 1099511603200 || tokenId == 1099511607296 || tokenId == 1099511611392 || tokenId == 1099511615488 || tokenId == 1099511619584 || tokenId == 1099511623680; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Cryptopaka is Context, ERC721Enumerable, Ownable { string private _baseTokenURI = "https://api.cryptopaka.com/token/"; bool private _paused = true; uint256 private _lastTimestamp = 0; uint256 private _lastPrice = 10000 gwei; uint256 public constant basePrice = 10000 gwei; bytes32 public searchSeed = 0x0; // prevent "premining" // used to verify the parser bytes32 public constant jsSHA256 = 0x1288f5184d996524ea5f6e6d51fc46548caced33616e91dcfe205189d1a03e2e; constructor() ERC721("Cryptopaka", "CPK") {} /** * @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); /** * @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(), "paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused(), "not paused"); _; } /** * @dev Triggers stopped state. */ function pause() public whenNotPaused onlyOwner { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function unpause() public whenPaused onlyOwner { searchSeed = blockhash(block.number - 1); _paused = false; emit Unpaused(_msgSender()); } /** * @dev See {ERC721-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory uri) public onlyOwner { _baseTokenURI = uri; // we will change to a decentralized solution } /** * @dev Returns the current minting cost of a single paka */ function price() public view returns (uint256) { uint256 discount = (block.timestamp - _lastTimestamp) * 1 gwei; // 1 gwei/s if (_lastPrice > 100000000000000000) { discount *= 100; // if price > 0.1 eth then increase the discount } uint256 ret = (_lastPrice * 6) / 5; // 1.2 if (discount >= ret - basePrice) { return basePrice; // minimum price } ret -= discount; if (ret > 690000000000000000) { return 690000000000000000; // clamped at 0.69 eth } return ret; } function mint(bytes32 seed) public payable { uint256 p = price(); require(totalSupply() <= 142053); // 142053 + 16 genesis pakas = 142069 require(p <= msg.value, "ether below range"); // you could pay a bit more require(p * 2 > msg.value, "ether above range"); // but not too much _lastTimestamp = block.timestamp; _lastPrice = p; bytes32 h = keccak256(abi.encodePacked(seed, searchSeed)); require(h[29] | h[30] | h[31] == 0x0, "invalid seed"); uint256 tokenId = uint256(h >> 216); // genesis paka are not mintable require(!isGenesis(tokenId)); _mint(_msgSender(), tokenId); } function mintGenesis(uint256 tokenId) public onlyOwner { require(isGenesis(tokenId)); // owner can only mint genesis pakas _mint(_msgSender(), tokenId); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(_msgSender()).transfer(balance); } function isGenesis(uint256 tokenId) public pure returns (bool) { return tokenId == 1099511562240 || tokenId == 1099511566336 || tokenId == 1099511570432 || tokenId == 1099511574528 || tokenId == 1099511578624 || tokenId == 1099511582720 || tokenId == 1099511586816 || tokenId == 1099511590912 || tokenId == 1099511595008 || tokenId == 1099511599104 || tokenId == 1099511603200 || tokenId == 1099511607296 || tokenId == 1099511611392 || tokenId == 1099511615488 || tokenId == 1099511619584 || tokenId == 1099511623680; } } // 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}. 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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @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; } } // SPDX-License-Identifier: MIT 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); } } // 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); }
Returns the current minting cost of a single paka/
function price() public view returns (uint256) { if (_lastPrice > 100000000000000000) { } if (discount >= ret - basePrice) { } ret -= discount; if (ret > 690000000000000000) { } return ret; }
1,352,880
// File: contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } } library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 c = a - b; return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint64 a, uint64 b, string memory errorMessage) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function allowedToCatgorize() public view returns(uint roleId); /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint); } // File: contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract IMaster { mapping(address => bool) public whitelistedSponsor; function dAppToken() public view returns(address); function isInternal(address _address) public view returns(bool); function getLatestAddress(bytes2 _module) public view returns(address); function isAuthorizedToGovern(address _toCheck) public view returns(bool); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: contracts/external/proxy/Proxy.sol pragma solidity 0.5.7; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () external payable { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); } // File: contracts/external/proxy/UpgradeabilityProxy.sol pragma solidity 0.5.7; /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant IMPLEMENTATION_POSITION = keccak256("org.govblocks.proxy.implementation"); /** * @dev Constructor function */ constructor() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = IMPLEMENTATION_POSITION; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param _newImplementation address representing the new implementation to be set */ function _setImplementation(address _newImplementation) internal { bytes32 position = IMPLEMENTATION_POSITION; assembly { sstore(position, _newImplementation) } } /** * @dev Upgrades the implementation address * @param _newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address _newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != _newImplementation); _setImplementation(_newImplementation); emit Upgraded(_newImplementation); } } // File: contracts/external/proxy/OwnedUpgradeabilityProxy.sol pragma solidity 0.5.7; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation representing the address of the new implementation to be set. */ function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } } // File: contracts/interfaces/IToken.sol pragma solidity 0.5.7; contract IToken { function decimals() external view returns(uint8); /** * @dev Total number of tokens in existence */ function totalSupply() external view returns (uint256); /** * @dev Gets the balance of the specified address. * @param account The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address account) external view returns (uint256); /** * @dev Transfer token for a specified address * @param recipient The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) external returns (bool); /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) external; /** * @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. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Transfer tokens from one address to another * @param sender address The address which you want to send tokens from * @param recipient address The address which you want to transfer to * @param amount uint256 the amount of tokens to be transferred */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // File: contracts/interfaces/IMarket.sol pragma solidity 0.5.7; contract IMarket { enum PredictionStatus { Live, InSettlement, Cooling, InDispute, Settled } struct MarketData { uint64 startTime; uint64 predictionTime; uint64 neutralMinValue; uint64 neutralMaxValue; } struct MarketSettleData { uint64 WinningOption; uint64 settleTime; } MarketSettleData public marketSettleData; MarketData public marketData; function WinningOption() public view returns(uint256); function marketCurrency() public view returns(bytes32); function getMarketFeedData() public view returns(uint8, bytes32, address); function settleMarket() external; function getTotalStakedValueInPLOT() external view returns(uint256); /** * @dev Initialize the market. * @param _startTime The time at which market will create. * @param _predictionTime The time duration of market. * @param _minValue The minimum value of middle option range. * @param _maxValue The maximum value of middle option range. */ function initiate(uint64 _startTime, uint64 _predictionTime, uint64 _minValue, uint64 _maxValue) public payable; /** * @dev Resolve the dispute if wrong value passed at the time of market result declaration. * @param accepted The flag defining that the dispute raised is accepted or not * @param finalResult The final correct value of market currency. */ function resolveDispute(bool accepted, uint256 finalResult) external payable; /** * @dev Gets the market data. * @return _marketCurrency bytes32 representing the currency or stock name of the market. * @return minvalue uint[] memory representing the minimum range of all the options of the market. * @return maxvalue uint[] memory representing the maximum range of all the options of the market. * @return _optionPrice uint[] memory representing the option price of each option ranges of the market. * @return _ethStaked uint[] memory representing the ether staked on each option ranges of the market. * @return _plotStaked uint[] memory representing the plot staked on each option ranges of the market. * @return _predictionType uint representing the type of market. * @return _expireTime uint representing the expire time of the market. * @return _predictionStatus uint representing the status of the market. */ function getData() external view returns ( bytes32 _marketCurrency,uint[] memory minvalue,uint[] memory maxvalue, uint[] memory _optionPrice, uint[] memory _ethStaked, uint[] memory _plotStaked,uint _predictionType, uint _expireTime, uint _predictionStatus ); // /** // * @dev Gets the pending return. // * @param _user The address to specify the return of. // * @return uint representing the pending return amount. // */ // function getPendingReturn(address _user) external view returns(uint[] memory returnAmount, address[] memory _predictionAssets, uint[] memory incentive, address[] memory _incentiveTokens); /** * @dev Claim the return amount of the specified address. * @param _user The address to query the claim return amount of. * @return Flag, if 0:cannot claim, 1: Already Claimed, 2: Claimed */ function claimReturn(address payable _user) public returns(uint256); } // File: contracts/interfaces/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { /** * @dev change master address */ function setMasterAddress() public; } // File: contracts/interfaces/IMarketUtility.sol pragma solidity 0.5.7; contract IMarketUtility { function initialize(address payable[] calldata _addressParams, address _initiater) external; /** * @dev to Set authorized address to update parameters */ function setAuthorizedAddres() public; /** * @dev to update uint parameters in Market Config */ function updateUintParameters(bytes8 code, uint256 value) external; /** * @dev to Update address parameters in Market Config */ function updateAddressParameters(bytes8 code, address payable value) external; /** * @dev Get Parameters required to initiate market * @return Addresses of tokens to be distributed as incentives * @return Cool down time for market * @return Rate * @return Commission percent for predictions with ETH * @return Commission percent for predictions with PLOT **/ function getMarketInitialParams() public view returns(address[] memory, uint , uint, uint, uint); function getAssetPriceUSD(address _currencyAddress) external view returns(uint latestAnswer); function getPriceFeedDecimals(address _priceFeed) public view returns(uint8); function getValueAndMultiplierParameters(address _asset, uint256 _amount) public view returns (uint256, uint256); function update() external; function calculatePredictionValue(uint[] memory params, address asset, address user, address marketFeedAddress, bool _checkMultiplier) public view returns(uint _predictionValue, bool _multiplierApplied); /** * @dev Get basic market details * @return Minimum amount required to predict in market * @return Percentage of users leveraged amount to deduct when placed in wrong prediction * @return Decimal points for prediction positions **/ function getBasicMarketDetails() public view returns ( uint256, uint256, uint256, uint256 ); function getDisputeResolutionParams() public view returns (uint256); function calculateOptionPrice(uint[] memory params, address marketFeedAddress) public view returns(uint _optionPrice); /** * @dev Get price of provided feed address * @param _currencyFeedAddress Feed Address of currency on which market options are based on * @return Current price of the market currency **/ function getSettlemetPrice( address _currencyFeedAddress, uint256 _settleTime ) public view returns (uint256 latestAnswer, uint256 roundId); } // File: contracts/MarketRegistry.sol /* Copyright (C) 2020 PlotX.io 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.5.7; contract MarketRegistry is Governed, Iupgradable { using SafeMath for *; enum MarketType { HourlyMarket, DailyMarket, WeeklyMarket } struct MarketTypeData { uint64 predictionTime; uint64 optionRangePerc; } struct MarketCurrency { address marketImplementation; uint8 decimals; } struct MarketCreationData { uint64 initialStartTime; address marketAddress; address penultimateMarket; } struct DisputeStake { uint64 proposalId; address staker; uint256 stakeAmount; uint256 ethDeposited; uint256 tokenDeposited; } struct MarketData { bool isMarket; DisputeStake disputeStakes; } struct UserData { uint256 lastClaimedIndex; uint256 marketsCreated; uint256 totalEthStaked; uint256 totalPlotStaked; address[] marketsParticipated; mapping(address => bool) marketsParticipatedFlag; } uint internal marketCreationIncentive; mapping(address => MarketData) marketData; mapping(address => UserData) userData; mapping(uint256 => mapping(uint256 => MarketCreationData)) public marketCreationData; mapping(uint64 => address) disputeProposalId; address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal marketInitiater; address public tokenController; MarketCurrency[] marketCurrencies; MarketTypeData[] marketTypes; bool public marketCreationPaused; IToken public plotToken; IMarketUtility public marketUtility; IGovernance internal governance; IMaster ms; event MarketQuestion(address indexed marketAdd, bytes32 stockName, uint256 indexed predictionType, uint256 startTime); event PlacePrediction(address indexed user,uint256 value, uint256 predictionPoints, address predictionAsset,uint256 prediction,address indexed marketAdd,uint256 _leverage); event MarketResult(address indexed marketAdd, uint256[] totalReward, uint256 winningOption, uint256 closeValue, uint256 roundId); event Claimed(address indexed marketAdd, address indexed user, uint256[] reward, address[] _predictionAssets, uint256 incentive, address incentiveToken); event MarketTypes(uint256 indexed index, uint64 predictionTime, uint64 optionRangePerc); event MarketCurrencies(uint256 indexed index, address marketImplementation, address feedAddress, bytes32 currencyName); event DisputeRaised(address indexed marketAdd, address raisedBy, uint64 proposalId, uint256 proposedValue); event DisputeResolved(address indexed marketAdd, bool status); /** * @dev Checks if given addres is valid market address. */ function isMarket(address _address) public view returns(bool) { return marketData[_address].isMarket; } function isWhitelistedSponsor(address _address) public view returns(bool) { return ms.whitelistedSponsor(_address); } /** * @dev Initialize the PlotX MarketRegistry. * @param _defaultAddress Address authorized to start initial markets * @param _marketUtility The address of market config. * @param _plotToken The instance of PlotX token. */ function initiate(address _defaultAddress, address _marketUtility, address _plotToken, address payable[] memory _configParams) public { require(address(ms) == msg.sender); marketCreationIncentive = 50 ether; plotToken = IToken(_plotToken); address tcAddress = ms.getLatestAddress("TC"); tokenController = tcAddress; marketUtility = IMarketUtility(_generateProxy(_marketUtility)); marketUtility.initialize(_configParams, _defaultAddress); marketInitiater = _defaultAddress; } /** * @dev Start the initial market. */ function addInitialMarketTypesAndStart(uint64 _marketStartTime, address _ethMarketImplementation, address _btcMarketImplementation) external { require(marketInitiater == msg.sender); require(marketTypes.length == 0); _addNewMarketCurrency(_ethMarketImplementation); _addNewMarketCurrency(_btcMarketImplementation); _addMarket(1 hours, 50); _addMarket(24 hours, 200); _addMarket(7 days, 500); for(uint256 i = 0;i < marketTypes.length; i++) { marketCreationData[i][0].initialStartTime = _marketStartTime; marketCreationData[i][1].initialStartTime = _marketStartTime; createMarket(i, 0); createMarket(i, 1); } } /** * @dev Add new market type. * @param _predictionTime The time duration of market. * @param _marketStartTime The time at which market will create. * @param _optionRangePerc Option range percent of neutral min, max options (raised by 2 decimals) */ function addNewMarketType(uint64 _predictionTime, uint64 _marketStartTime, uint64 _optionRangePerc) external onlyAuthorizedToGovern { require(_marketStartTime > now); uint256 _marketType = marketTypes.length; _addMarket(_predictionTime, _optionRangePerc); for(uint256 j = 0;j < marketCurrencies.length; j++) { marketCreationData[_marketType][j].initialStartTime = _marketStartTime; createMarket(_marketType, j); } } /** * @dev Internal function to add market type * @param _predictionTime The time duration of market. * @param _optionRangePerc Option range percent of neutral min, max options (raised by 2 decimals) */ function _addMarket(uint64 _predictionTime, uint64 _optionRangePerc) internal { uint256 _marketType = marketTypes.length; marketTypes.push(MarketTypeData(_predictionTime, _optionRangePerc)); emit MarketTypes(_marketType, _predictionTime, _optionRangePerc); } /** * @dev Add new market currency. */ function addNewMarketCurrency(address _marketImplementation, uint64 _marketStartTime) external onlyAuthorizedToGovern { uint256 _marketCurrencyIndex = marketCurrencies.length; _addNewMarketCurrency(_marketImplementation); for(uint256 j = 0;j < marketTypes.length; j++) { marketCreationData[j][_marketCurrencyIndex].initialStartTime = _marketStartTime; createMarket(j, _marketCurrencyIndex); } } function _addNewMarketCurrency(address _marketImplementation) internal { uint256 _marketCurrencyIndex = marketCurrencies.length; (, bytes32 _currencyName, address _priceFeed) = IMarket(_marketImplementation).getMarketFeedData(); uint8 _decimals = marketUtility.getPriceFeedDecimals(_priceFeed); marketCurrencies.push(MarketCurrency(_marketImplementation, _decimals)); emit MarketCurrencies(_marketCurrencyIndex, _marketImplementation, _priceFeed, _currencyName); } /** * @dev Update the implementations of the market. */ function updateMarketImplementations(uint256[] calldata _currencyIndexes, address[] calldata _marketImplementations) external onlyAuthorizedToGovern { require(_currencyIndexes.length == _marketImplementations.length); for(uint256 i = 0;i< _currencyIndexes.length; i++) { (, , address _priceFeed) = IMarket(_marketImplementations[i]).getMarketFeedData(); uint8 _decimals = marketUtility.getPriceFeedDecimals(_priceFeed); marketCurrencies[_currencyIndexes[i]] = MarketCurrency(_marketImplementations[i], _decimals); } } /** * @dev Upgrade the implementations of the contract. * @param _proxyAddress the proxy address. * @param _newImplementation Address of new implementation contract */ function upgradeContractImplementation(address payable _proxyAddress, address _newImplementation) external onlyAuthorizedToGovern { require(_newImplementation != address(0)); OwnedUpgradeabilityProxy tempInstance = OwnedUpgradeabilityProxy(_proxyAddress); tempInstance.upgradeTo(_newImplementation); } /** * @dev Changes the master address and update it's instance */ function setMasterAddress() public { OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(address(uint160(address(this)))); require(msg.sender == proxy.proxyOwner(),"Sender is not proxy owner."); ms = IMaster(msg.sender); masterAddress = msg.sender; governance = IGovernance(ms.getLatestAddress("GV")); } /** * @dev Creates the new market. * @param _marketType The type of the market. * @param _marketCurrencyIndex the index of market currency. */ function _createMarket(uint256 _marketType, uint256 _marketCurrencyIndex, uint64 _minValue, uint64 _maxValue, uint64 _marketStartTime, bytes32 _currencyName) internal { require(!marketCreationPaused); MarketTypeData memory _marketTypeData = marketTypes[_marketType]; address payable _market = _generateProxy(marketCurrencies[_marketCurrencyIndex].marketImplementation); marketData[_market].isMarket = true; IMarket(_market).initiate(_marketStartTime, _marketTypeData.predictionTime, _minValue, _maxValue); emit MarketQuestion(_market, _currencyName, _marketType, _marketStartTime); (marketCreationData[_marketType][_marketCurrencyIndex].penultimateMarket, marketCreationData[_marketType][_marketCurrencyIndex].marketAddress) = (marketCreationData[_marketType][_marketCurrencyIndex].marketAddress, _market); } /** * @dev Creates the new market * @param _marketType The type of the market. * @param _marketCurrencyIndex the index of market currency. */ function createMarket(uint256 _marketType, uint256 _marketCurrencyIndex) public payable{ address penultimateMarket = marketCreationData[_marketType][_marketCurrencyIndex].penultimateMarket; if(penultimateMarket != address(0)) { IMarket(penultimateMarket).settleMarket(); } if(marketCreationData[_marketType][_marketCurrencyIndex].marketAddress != address(0)) { (,,,,,,,, uint _status) = getMarketDetails(marketCreationData[_marketType][_marketCurrencyIndex].marketAddress); require(_status >= uint(IMarket.PredictionStatus.InSettlement)); } (uint8 _roundOfToNearest, bytes32 _currencyName, address _priceFeed) = IMarket(marketCurrencies[_marketCurrencyIndex].marketImplementation).getMarketFeedData(); marketUtility.update(); uint64 _marketStartTime = calculateStartTimeForMarket(_marketType, _marketCurrencyIndex); uint64 _optionRangePerc = marketTypes[_marketType].optionRangePerc; uint currentPrice = marketUtility.getAssetPriceUSD(_priceFeed); _optionRangePerc = uint64(currentPrice.mul(_optionRangePerc.div(2)).div(10000)); uint64 _decimals = marketCurrencies[_marketCurrencyIndex].decimals; uint64 _minValue = uint64((ceil(currentPrice.sub(_optionRangePerc).div(_roundOfToNearest), 10**_decimals)).mul(_roundOfToNearest)); uint64 _maxValue = uint64((ceil(currentPrice.add(_optionRangePerc).div(_roundOfToNearest), 10**_decimals)).mul(_roundOfToNearest)); _createMarket(_marketType, _marketCurrencyIndex, _minValue, _maxValue, _marketStartTime, _currencyName); userData[msg.sender].marketsCreated++; } /** * @dev function to reward user for initiating market creation calls */ function claimCreationReward() external { require(userData[msg.sender].marketsCreated > 0); uint256 pendingReward = marketCreationIncentive.mul(userData[msg.sender].marketsCreated); require(plotToken.balanceOf(address(this)) > pendingReward); delete userData[msg.sender].marketsCreated; _transferAsset(address(plotToken), msg.sender, pendingReward); } function calculateStartTimeForMarket(uint256 _marketType, uint256 _marketCurrencyIndex) public view returns(uint64 _marketStartTime) { address previousMarket = marketCreationData[_marketType][_marketCurrencyIndex].marketAddress; if(previousMarket != address(0)) { (_marketStartTime, , , ) = IMarket(previousMarket).marketData(); } else { _marketStartTime = marketCreationData[_marketType][_marketCurrencyIndex].initialStartTime; } uint predictionTime = marketTypes[_marketType].predictionTime; if(now > _marketStartTime.add(predictionTime)) { uint noOfMarketsSkipped = ((now).sub(_marketStartTime)).div(predictionTime); _marketStartTime = uint64(_marketStartTime.add(noOfMarketsSkipped.mul(predictionTime))); } } /** * @dev Updates Flag to pause creation of market. */ function pauseMarketCreation() external onlyAuthorizedToGovern { require(!marketCreationPaused); marketCreationPaused = true; } /** * @dev Updates Flag to resume creation of market. */ function resumeMarketCreation() external onlyAuthorizedToGovern { require(marketCreationPaused); marketCreationPaused = false; } /** * @dev Create proposal if user wants to raise the dispute. * @param proposalTitle The title of proposal created by user. * @param description The description of dispute. * @param solutionHash The ipfs solution hash. * @param action The encoded action for solution. * @param _stakeForDispute The token staked to raise the diospute. * @param _user The address who raises the dispute. */ function createGovernanceProposal(string memory proposalTitle, string memory description, string memory solutionHash, bytes memory action, uint256 _stakeForDispute, address _user, uint256 _ethSentToPool, uint256 _tokenSentToPool, uint256 _proposedValue) public { require(isMarket(msg.sender)); uint64 proposalId = uint64(governance.getProposalLength()); marketData[msg.sender].disputeStakes = DisputeStake(proposalId, _user, _stakeForDispute, _ethSentToPool, _tokenSentToPool); disputeProposalId[proposalId] = msg.sender; governance.createProposalwithSolution(proposalTitle, proposalTitle, description, 10, solutionHash, action); emit DisputeRaised(msg.sender, _user, proposalId, _proposedValue); } /** * @dev Resolve the dispute if wrong value passed at the time of market result declaration. * @param _marketAddress The address specify the market. * @param _result The final result of the market. */ function resolveDispute(address payable _marketAddress, uint256 _result) external onlyAuthorizedToGovern { uint256 ethDepositedInPool = marketData[_marketAddress].disputeStakes.ethDeposited; uint256 plotDepositedInPool = marketData[_marketAddress].disputeStakes.tokenDeposited; uint256 stakedAmount = marketData[_marketAddress].disputeStakes.stakeAmount; address payable staker = address(uint160(marketData[_marketAddress].disputeStakes.staker)); address plotTokenAddress = address(plotToken); _transferAsset(plotTokenAddress, _marketAddress, plotDepositedInPool); IMarket(_marketAddress).resolveDispute.value(ethDepositedInPool)(true, _result); emit DisputeResolved(_marketAddress, true); _transferAsset(plotTokenAddress, staker, stakedAmount); } /** * @dev Burns the tokens of member who raised the dispute, if dispute is rejected. * @param _proposalId Id of dispute resolution proposal */ function burnDisputedProposalTokens(uint _proposalId) external onlyAuthorizedToGovern { address disputedMarket = disputeProposalId[uint64(_proposalId)]; IMarket(disputedMarket).resolveDispute(false, 0); emit DisputeResolved(disputedMarket, false); uint _stakedAmount = marketData[disputedMarket].disputeStakes.stakeAmount; plotToken.burn(_stakedAmount); } /** * @dev Claim the pending return of the market. * @param maxRecords Maximum number of records to claim reward for */ function claimPendingReturn(uint256 maxRecords) external { uint256 i; uint len = userData[msg.sender].marketsParticipated.length; uint lastClaimed = len; uint count; for(i = userData[msg.sender].lastClaimedIndex; i < len && count < maxRecords; i++) { if(IMarket(userData[msg.sender].marketsParticipated[i]).claimReturn(msg.sender) > 0) { count++; } else { if(lastClaimed == len) { lastClaimed = i; } } } if(lastClaimed == len) { lastClaimed = i; } userData[msg.sender].lastClaimedIndex = lastClaimed; } function () external payable { } /** * @dev Transfer `_amount` number of market registry assets contract to `_to` address */ function transferAssets(address _asset, address payable _to, uint _amount) external onlyAuthorizedToGovern { _transferAsset(_asset, _to, _amount); } /** * @dev Transfer the assets to specified address. * @param _asset The asset transfer to the specific address. * @param _recipient The address to transfer the asset of * @param _amount The amount which is transfer. */ function _transferAsset(address _asset, address payable _recipient, uint256 _amount) internal { if(_amount > 0) { if(_asset == ETH_ADDRESS) { _recipient.transfer(_amount); } else { require(IToken(_asset).transfer(_recipient, _amount)); } } } function updateUintParameters(bytes8 code, uint256 value) external onlyAuthorizedToGovern { if(code == "MCRINC") { // Incentive to be distributed to user for market creation marketCreationIncentive = value; } else { marketUtility.updateUintParameters(code, value); } } function updateConfigAddressParameters(bytes8 code, address payable value) external onlyAuthorizedToGovern { marketUtility.updateAddressParameters(code, value); } /** * @dev to generater proxy * @param _contractAddress of the proxy */ function _generateProxy(address _contractAddress) internal returns(address payable) { OwnedUpgradeabilityProxy tempInstance = new OwnedUpgradeabilityProxy(_contractAddress); return address(tempInstance); } /** * @dev Emits the MarketResult event. * @param _totalReward The amount of reward to be distribute. * @param winningOption The winning option of the market. * @param closeValue The closing value of the market currency. */ function callMarketResultEvent(uint256[] calldata _totalReward, uint256 winningOption, uint256 closeValue, uint _roundId) external { require(isMarket(msg.sender)); emit MarketResult(msg.sender, _totalReward, winningOption, closeValue, _roundId); } /** * @dev Emits the PlacePrediction event and sets the user data. * @param _user The address who placed prediction. * @param _value The amount of ether user staked. * @param _predictionPoints The positions user will get. * @param _predictionAsset The prediction assets user will get. * @param _prediction The option range on which user placed prediction. * @param _leverage The leverage selected by user at the time of place prediction. */ function setUserGlobalPredictionData(address _user,uint256 _value, uint256 _predictionPoints, address _predictionAsset, uint256 _prediction, uint256 _leverage) external { require(isMarket(msg.sender)); if(_predictionAsset == ETH_ADDRESS) { userData[_user].totalEthStaked = userData[_user].totalEthStaked.add(_value); } else { userData[_user].totalPlotStaked = userData[_user].totalPlotStaked.add(_value); } if(!userData[_user].marketsParticipatedFlag[msg.sender]) { userData[_user].marketsParticipated.push(msg.sender); userData[_user].marketsParticipatedFlag[msg.sender] = true; } emit PlacePrediction(_user, _value, _predictionPoints, _predictionAsset, _prediction, msg.sender,_leverage); } /** * @dev Emits the claimed event. * @param _user The address who claim their reward. * @param _reward The reward which is claimed by user. * @param predictionAssets The prediction assets of user. * @param incentives The incentives of user. * @param incentiveToken The incentive tokens of user. */ function callClaimedEvent(address _user ,uint[] calldata _reward, address[] calldata predictionAssets, uint incentives, address incentiveToken) external { require(isMarket(msg.sender)); emit Claimed(msg.sender, _user, _reward, predictionAssets, incentives, incentiveToken); } /** * @dev Get uint config parameters */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint256 value) { if(code == "MCRINC") { codeVal = code; value = marketCreationIncentive; } } /** * @dev Gets the market details of the specified address. * @param _marketAdd The market address to query the details of market. * @return _feedsource bytes32 representing the currency or stock name of the market. * @return minvalue uint[] memory representing the minimum range of all the options of the market. * @return maxvalue uint[] memory representing the maximum range of all the options of the market. * @return optionprice uint[] memory representing the option price of each option ranges of the market. * @return _ethStaked uint[] memory representing the ether staked on each option ranges of the market. * @return _plotStaked uint[] memory representing the plot staked on each option ranges of the market. * @return _predictionType uint representing the type of market. * @return _expireTime uint representing the expire time of the market. * @return _predictionStatus uint representing the status of the market. */ function getMarketDetails(address _marketAdd)public view returns (bytes32 _feedsource,uint256[] memory minvalue,uint256[] memory maxvalue, uint256[] memory optionprice,uint256[] memory _ethStaked, uint256[] memory _plotStaked,uint256 _predictionType,uint256 _expireTime, uint256 _predictionStatus){ return IMarket(_marketAdd).getData(); } /** * @dev Get total assets staked by user in PlotX platform * @return _plotStaked Total PLOT staked by user * @return _ethStaked Total ETH staked by user */ function getTotalAssetStakedByUser(address _user) external view returns(uint256 _plotStaked, uint256 _ethStaked) { return (userData[_user].totalPlotStaked, userData[_user].totalEthStaked); } /** * @dev Gets the market details of the specified user address. * @param user The address to query the details of market. * @param fromIndex The index to query the details from. * @param toIndex The index to query the details to * @return _market address[] memory representing the address of the market. * @return _winnigOption uint256[] memory representing the winning option range of the market. */ function getMarketDetailsUser(address user, uint256 fromIndex, uint256 toIndex) external view returns (address[] memory _market, uint256[] memory _winnigOption){ uint256 totalMarketParticipated = userData[user].marketsParticipated.length; if(totalMarketParticipated > 0 && fromIndex < totalMarketParticipated) { uint256 _toIndex = toIndex; if(_toIndex >= totalMarketParticipated) { _toIndex = totalMarketParticipated - 1; } _market = new address[](_toIndex.sub(fromIndex).add(1)); _winnigOption = new uint256[](_toIndex.sub(fromIndex).add(1)); for(uint256 i = fromIndex; i <= _toIndex; i++) { _market[i] = userData[user].marketsParticipated[i]; (_winnigOption[i], ) = IMarket(_market[i]).marketSettleData(); } } } /** * @dev Gets the addresses of open markets. * @return _openMarkets address[] memory representing the open market addresses. * @return _marketTypes uint256[] memory representing the open market types. */ function getOpenMarkets() external view returns(address[] memory _openMarkets, uint256[] memory _marketTypes, bytes32[] memory _marketCurrencies) { uint256 count = 0; uint256 marketTypeLength = marketTypes.length; uint256 marketCurrencyLength = marketCurrencies.length; _openMarkets = new address[]((marketTypeLength).mul(marketCurrencyLength)); _marketTypes = new uint256[]((marketTypeLength).mul(marketCurrencyLength)); _marketCurrencies = new bytes32[]((marketTypeLength).mul(marketCurrencyLength)); for(uint256 i = 0; i< marketTypeLength; i++) { for(uint256 j = 0; j< marketCurrencyLength; j++) { _openMarkets[count] = marketCreationData[i][j].marketAddress; _marketTypes[count] = i; _marketCurrencies[count] = IMarket(marketCurrencies[j].marketImplementation).marketCurrency(); count++; } } } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { return ((a + m - 1) / m) * m; } // /** // * @dev Calculates the user pending return amount. // * @param _user The address to query the pending return amount of. // * @return pendingReturn uint256 representing the pending return amount of user. // * @return incentive uint256 representing the incentive. // */ // function calculateUserPendingReturn(address _user) external view returns(uint[] memory returnAmount, address[] memory _predictionAssets, uint[] memory incentive, address[] memory _incentiveTokens) { // uint256 _return; // uint256 _incentive; // for(uint256 i = lastClaimedIndex[_user]; i < marketsParticipated[_user].length; i++) { // // pendingReturn = pendingReturn.add(marketsParticipated[_user][i].call(abi.encodeWithSignature("getPendingReturn(uint256)", _user))); // (_return, _incentive) = IMarket(marketsParticipated[_user][i]).getPendingReturn(_user); // pendingReturn = pendingReturn.add(_return); // incentive = incentive.add(_incentive); // } // } }
Gets the addresses of open markets. return _openMarkets address[] memory representing the open market addresses. return _marketTypes uint256[] memory representing the open market types./
function getOpenMarkets() external view returns(address[] memory _openMarkets, uint256[] memory _marketTypes, bytes32[] memory _marketCurrencies) { uint256 count = 0; uint256 marketTypeLength = marketTypes.length; uint256 marketCurrencyLength = marketCurrencies.length; _openMarkets = new address[]((marketTypeLength).mul(marketCurrencyLength)); _marketTypes = new uint256[]((marketTypeLength).mul(marketCurrencyLength)); _marketCurrencies = new bytes32[]((marketTypeLength).mul(marketCurrencyLength)); for(uint256 i = 0; i< marketTypeLength; i++) { for(uint256 j = 0; j< marketCurrencyLength; j++) { _openMarkets[count] = marketCreationData[i][j].marketAddress; _marketTypes[count] = i; _marketCurrencies[count] = IMarket(marketCurrencies[j].marketImplementation).marketCurrency(); count++; } } for(uint256 i = 0; i< marketTypeLength; i++) { for(uint256 j = 0; j< marketCurrencyLength; j++) { _openMarkets[count] = marketCreationData[i][j].marketAddress; _marketTypes[count] = i; _marketCurrencies[count] = IMarket(marketCurrencies[j].marketImplementation).marketCurrency(); count++; } } }
10,840,479
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract Function { // Functions can return multiuple values. function returnMany() public pure returns ( uint, bool, uint ) { return(1, true, 2); } // Return values can be named. function named() public pure returns ( uint x, bool y, uint z ) { return (1, true, 2); } // Return value can be assigned to their name. // In this case the return statement can be omitted. function assigned() public pure returns ( uint x, bool y, uint z ) { x = 1; y = true; z = 2; } // Use destructuring assignment when calling another // function that returns multiple function destructoringAssignment() public pure returns ( uint, bool, uint, uint, uint ) { (uint a,bool b,uint c) = returnMany(); // Value can be left out. (uint d, ,uint e) = (4, 5, 6); return (a, b, c, d, e); } // Cannot use map for either input or output // Can use array for input function arrayInput(uint[] memory _arr) public {} // map 不能用ζ₯δ½œδΈΊθΎ“ε…₯ζˆ–θ€…θΎ“ε‡Ί // εŒ…ε«(塌ε₯—)ζ˜ ε°„ηš„η±»εž‹εͺθƒ½ζ˜―ε†…ιƒ¨ε‡½ζ•°ζˆ–εΊ“ε‡½ζ•°ηš„ε‚ζ•°ζˆ–θΏ”ε›žε˜ι‡γ€‚ // θΎ“ε…₯οΌšδ½œδΈΊε‡½ζ•°ε‚ζ•°θΎ“ε…₯οΌŒθΎ“ε‡ΊοΌšδ½œδΈΊε‡½ζ•°θΏ”ε›žε€ΌθΎ“ε‡Ί // function mapInput(mapping(uint => address) memory _map) public {} // Can use array for output uint[] public arr; function arrayOutput() public view returns (uint[] memory) { return arr; } }
Can use array for input
function arrayInput(uint[] memory _arr) public {}
1,798,202
./full_match/100/0x698140674AaA4b3e66BD80116013bdB67D32Bad1/sources/project_/contracts/base/BaseController.sol
Transfer the manager to a new address Only one manager can presently be set _manager - New manager./
function transferManagement(address _manager) public restricted { manager = _manager; }
14,266,205
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./interfaces/IPWPegger.sol"; import "./interfaces/ICalibratorProxy.sol"; import "./interfaces/IEACAggregatorProxy.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./libraries/PWLibrary.sol"; import "./libraries/PWConfig.sol"; import "hardhat/console.sol"; struct PoolData { uint g; uint u; uint p1; uint lp; } contract PWPegger is IPWPegger { PWConfig private pwconfig; bool statusPause; uint round; modifier onlyAdmin() { require(msg.sender == pwconfig.admin, "Error: must be admin EOA or multisig only"); _; } modifier onlyKeeper() { require(msg.sender == pwconfig.admin || msg.sender == pwconfig.keeper, "Error: must be admin or keeper EOA/multisig only"); _; } modifier onlyNotPaused() { require(!statusPause, "PWPeggerMock in on Pause now"); _; } constructor(PWConfig memory _pwconfig) { uint _dec = _pwconfig.decimals; require( _dec > 0 && _pwconfig.frontrunth > 0 && _pwconfig.volatilityth > _pwconfig.frontrunth && _pwconfig.emergencyth > _pwconfig.volatilityth, "Error: wrong config parameters. Check th params and decimals" ); // require(msg.sender != _pwconfig.admin, "Error: deployer cannot be an admin"); pwconfig = _pwconfig; statusPause = false; round = 0; } function updPWConfig(PWConfig memory _pwconfig) external onlyAdmin() { pwconfig = _pwconfig; } function updAdmin(address _newAdmin) external override onlyAdmin() { pwconfig.admin = _newAdmin; } function updKeeper(address _newKeeper) external override onlyAdmin() { pwconfig.keeper = _newKeeper; } function updPathwayDONRef(address _newPwpegdonRef) external override onlyAdmin() { pwconfig.pwpegdonRef = _newPwpegdonRef; } function updCalibratorProxyRef(address _newCalibrator) external override onlyAdmin() { pwconfig.calibrator = _newCalibrator; } function updVaultRef(address _newVault) external override onlyAdmin() { pwconfig.vault = _newVault; } function setPauseOn() external override onlyKeeper() onlyNotPaused() { statusPause = true; } function setPauseOff() external override onlyAdmin() { statusPause = false; } function getPauseStatus() external override view returns (bool) { return statusPause; } function updPoolRef(address _pool) external override onlyAdmin() { pwconfig.pool = _pool; } function updTokenRef(address _token) external override onlyAdmin() { pwconfig.token = _token; } function updEmergencyTh(uint _newEmergencyth) external override onlyAdmin() { pwconfig.emergencyth = _newEmergencyth; } function updVolatilityTh(uint _newVolatilityth) external override onlyAdmin() { pwconfig.volatilityth = _newVolatilityth; } function updFrontRunProtectionTh(uint _newFrontrunth) external override onlyAdmin() { pwconfig.frontrunth = _newFrontrunth; } function _checkThConditionsOrRaiseException(uint _currPrice, uint _pwPrice) view internal { // _currPrice and _pwPrice must be same decimals uint n = 10**pwconfig.decimals; uint priceDiff = _currPrice > _pwPrice ? n*(_currPrice - _pwPrice)/_currPrice : n*(_pwPrice - _currPrice)/_currPrice; require(priceDiff < pwconfig.emergencyth, "Th Emergency Error: price diff exceeds emergency threshold"); require(priceDiff >= pwconfig.volatilityth, "Th Volatility Error: price diff exceeds volatility threshold"); } function _checkThFrontrunOrRaiseException(uint _currPrice, uint _keeperPrice) view internal { // _currPrice and _keeperPrice must be same decimals uint n = 10**pwconfig.decimals; uint priceDiff = _currPrice > _keeperPrice ? n*(_currPrice - _keeperPrice)/_keeperPrice : n*(_keeperPrice - _currPrice)/_keeperPrice; require(priceDiff <= pwconfig.frontrunth, "Th FrontRun Error: current price is much higher than keeperPrice"); require(priceDiff < pwconfig.emergencyth, "Th Emergency Error: current price is much higher than keeperPrice"); } // those functions are reading and convert data to the correct decimals for price data function _readDONPrice(address _refDON) view internal returns (uint) { IEACAggregatorProxy priceFeed = IEACAggregatorProxy(_refDON); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = priceFeed.latestRoundData(); uint decimals = priceFeed.decimals(); require(decimals >= 0 && answer > 0, 'DON Error: price data and decimals must be higher than 0'); uint n = 10**pwconfig.decimals; uint d = 10**decimals; return (uint(answer)*n/d); } function _preparePWData(IUniswapV2Pair _pool, address _tokenGRef) view internal returns (PoolData memory) { ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ) = _pool.getReserves(); IERC20 tokenG = IERC20(_pool.token0() == _tokenGRef ? _pool.token0() : _pool.token1()); IERC20 tokenU = IERC20(!(_pool.token0() == _tokenGRef) ? _pool.token0() : _pool.token1()); uint decimalsG = uint(tokenG.decimals()); uint decimalsU = uint(tokenU.decimals()); uint n = 10**pwconfig.decimals; uint g = n*uint(_pool.token0() == _tokenGRef ? reserve0 : reserve1)/(10**decimalsG); uint u = n*uint(!(_pool.token0() == _tokenGRef) ? reserve0 : reserve1)/(10**decimalsU); return PoolData( g, u, n*u/g, _pool.totalSupply() ); } function callIntervention(uint _keeperCurrentPrice) external override onlyKeeper() onlyNotPaused() { require(_keeperCurrentPrice > 0, 'Call Error: _keeperCurrentPrice must be higher than 0'); IUniswapV2Pair pool = IUniswapV2Pair(pwconfig.pool); uint pPrice = _readDONPrice(pwconfig.pwpegdonRef); PoolData memory poolData = _preparePWData(pool, pwconfig.token); _checkThConditionsOrRaiseException(poolData.p1, pPrice); _checkThFrontrunOrRaiseException(poolData.p1, _keeperCurrentPrice); if (pPrice == poolData.p1) { revert("no price diff"); } // Step-I: what to do - up or down PWLibrary.EAction act = PWLibrary.findDirection(poolData.p1, pPrice); //p1 - prev price, pPrice - peg price console.log("computing PWLibrary.computeXLPForDirection"); console.log("poolData.g %s", poolData.g); console.log("poolData.u %s", poolData.u); console.log("poolData.p1 %s", poolData.p1); console.log("pPrice %s", pPrice); console.log("isUp?: %s", pPrice > poolData.p1); console.log("poolData.lp, %s", poolData.lp); console.log("pwconfig.decimals, %s", pwconfig.decimals); // Step-II: how many LPs uint xLPs = PWLibrary.computeXLPForDirection( poolData.g, poolData.u, poolData.p1, pPrice, act, poolData.lp, pwconfig.decimals ); console.log("xLPs, %s", xLPs); console.log("pwconfig.vault, %s", pwconfig.vault); // Step-II: execute: pool.transferFrom(pwconfig.vault, address(this), xLPs); pool.approve(address(pwconfig.calibrator), xLPs); ICalibratorProxy calibrator = ICalibratorProxy(pwconfig.calibrator); if (act == PWLibrary.EAction.Up) { calibrator.calibratePurelyViaPercentOfLPs_UP( pool, xLPs, 1, 1, pwconfig.vault ); } else if (act == PWLibrary.EAction.Down) { calibrator.calibratePurelyViaPercentOfLPs_DOWN( pool, xLPs, 1, 1, pwconfig.vault ); } else { revert("invalid pw action"); } } function getPWConfig() external override view returns (PWConfig memory) { return pwconfig; } function getLastRoundNumber() external override view returns (uint) { return round; } }
_currPrice and _keeperPrice must be same decimals
function _checkThFrontrunOrRaiseException(uint _currPrice, uint _keeperPrice) view internal { uint n = 10**pwconfig.decimals; uint priceDiff = _currPrice > _keeperPrice ? n*(_currPrice - _keeperPrice)/_keeperPrice : n*(_keeperPrice - _currPrice)/_keeperPrice; require(priceDiff <= pwconfig.frontrunth, "Th FrontRun Error: current price is much higher than keeperPrice"); require(priceDiff < pwconfig.emergencyth, "Th Emergency Error: current price is much higher than keeperPrice"); }
12,902,989
./partial_match/1/0x17378F524320b600a2EE64175CE72c5e84af358D/sources/contracts/StrategyBalancerBPT.sol
Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); IERC20(want).safeTransfer(_vault, balance); }
9,201,128
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {WadRayMath} from '../../libraries/math/WadRayMath.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; interface ILido { function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256); } /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AStETH is VersionedInitializable, IncentivizedERC20, IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant UINT_MAX_VALUE = uint256(-1); uint256 public constant ATOKEN_REVISION = 0x1; address public immutable UNDERLYING_ASSET_ADDRESS; address public immutable RESERVE_TREASURY_ADDRESS; ILendingPool public immutable POOL; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; modifier onlyLendingPool() { require(_msgSender() == address(POOL), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } constructor( ILendingPool pool, address underlyingAssetAddress, address reserveTreasuryAddress, string memory tokenName, string memory tokenSymbol, address incentivesController ) public IncentivizedERC20(tokenName, tokenSymbol, 18, incentivesController) { POOL = pool; UNDERLYING_ASSET_ADDRESS = underlyingAssetAddress; RESERVE_TREASURY_ADDRESS = reserveTreasuryAddress; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } function initialize( uint8 underlyingAssetDecimals, string calldata tokenName, string calldata tokenSymbol ) external virtual initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(tokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(tokenName); _setSymbol(tokenSymbol); _setDecimals(underlyingAssetDecimals); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(_stEthRebasingIndex()).rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(_stEthRebasingIndex()).rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(RESERVE_TREASURY_ADDRESS, amount.rayDiv(_stEthRebasingIndex()).rayDiv(index)); emit Transfer(address(0), RESERVE_TREASURY_ADDRESS, amount); emit Mint(RESERVE_TREASURY_ADDRESS, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return _scaledBalanceOf(user, _stEthRebasingIndex()).rayMul( POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS) ); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) public view override returns (uint256) { return _scaledBalanceOf(user, _stEthRebasingIndex()); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { uint256 rebasingIndex = _stEthRebasingIndex(); return (_scaledBalanceOf(user, rebasingIndex), _scaledTotalSupply(rebasingIndex)); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = _scaledTotalSupply(_stEthRebasingIndex()); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return _scaledTotalSupply(_stEthRebasingIndex()); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(target, amount); return amount; } /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { uint256 index = POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); uint256 rebasingIndex = _stEthRebasingIndex(); uint256 fromBalanceBefore = _scaledBalanceOf(from, rebasingIndex).rayMul(index); uint256 toBalanceBefore = _scaledBalanceOf(to, rebasingIndex).rayMul(index); super._transfer(from, to, amount.rayDiv(rebasingIndex).rayDiv(index)); if (validate) { POOL.finalizeTransfer( UNDERLYING_ASSET_ADDRESS, from, to, amount, fromBalanceBefore, toBalanceBefore ); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } /** * @return Current rebasin index of stETH in RAY **/ function _stEthRebasingIndex() internal view returns (uint256) { // Below expression returns how much Ether corresponds // to 10 ** 27 shares. 10 ** 27 was taken to provide // same precision as AAVE's liquidity index, which // counted in RAY's (decimals with 27 digits). return ILido(UNDERLYING_ASSET_ADDRESS).getPooledEthByShares(1e27); } function _scaledBalanceOf(address user, uint256 rebasingIndex) internal view returns (uint256) { return super.balanceOf(user).rayMul(rebasingIndex); } function _scaledTotalSupply(uint256 rebasingIndex) internal view returns (uint256) { return super.totalSupply().rayMul(rebasingIndex); } /** * @dev Returns the internal balance of the user. The internal balance is the balance of * the underlying asset of the user (sum of deposits of the user), divided by the current * liquidity index at the moment of the update and by the current stETH rebasing index. * @param user The user whose balance is calculated * @return The internal balance of the user **/ function internalBalanceOf(address user) external view returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the internal total supply of the token. Represents * sum(debt/_stEthRebasingIndex/liquidityIndex). * @return the internal total supply */ function internalTotalSupply() external view returns (uint256) { return super.totalSupply(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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 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.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; interface IAToken is IERC20, IScaledBalanceToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @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); /** * @dev Returns true if and only if the function is running in the constructor **/ function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; IAaveIncentivesController internal immutable _incentivesController; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals, address incentivesController ) public { _name = name; _symbol = symbol; _decimals = decimals; _incentivesController = IAaveIncentivesController(incentivesController); } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_incentivesController) != address(0)) { uint256 currentTotalSupply = _totalSupply; _incentivesController.handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _incentivesController.handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // 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: agpl-3.0 pragma solidity 0.6.12; /** * @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.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @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: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; }
Returns the internal total supply of the token. Represents sum(debt/_stEthRebasingIndex/liquidityIndex). return the internal total supply/
function internalTotalSupply() external view returns (uint256) { return super.totalSupply(); }
468,666
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 fromBlock; uint256 votes; } contract ProjectToken is IERC20, ReentrancyGuard { using SafeMath for uint256; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); uint256 public override totalSupply; string public symbol; uint8 public decimals; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; constructor(string memory _symbol) public { symbol = _symbol; decimals = 18; } function getChainId() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } return chainId; } function balanceOf(address account) public view override returns (uint256 free) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address account_owner, address spender) public view virtual override returns (uint256) { return _allowances[account_owner][spender]; } function approve(address spender, uint256 amount) public virtual override nonReentrant returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual nonReentrant returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual nonReentrant returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint256 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)) { uint256 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, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == block.number ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( block.number, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public nonReentrant { return _delegate(msg.sender, 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) { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "StakingToken: not yet determined"); uint256 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; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 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 = _balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual { // if (from == address(0)) { // // When minting tokens // uint256 newSupply = totalSupply().add(amount); // require( // newSupply <= _softcap && newSupply <= _cap, // "ERC20Capped: cap exceeded" // ); // } } function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual { _moveDelegates(from, to, amount); } function _approve( address account_owner, address spender, uint256 amount ) internal virtual { require( account_owner != address(0), "ERC20: approve from the zero address" ); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[account_owner][spender] = amount; emit Approval(account_owner, spender, 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); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); totalSupply = totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } }
Gets the current votes balance for `account` account The address to get votes balance return The number of current votes for `account`/
function getCurrentVotes(address account) external view returns (uint256) { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
1,758,305
./partial_match/1/0x1c0807B049bF710CdA67447766130BD7e1B30907/sources/BabyYoda.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Baby Yoda", "YODA") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyDevelopmentFee = 0; uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellDevelopmentFee = 0; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1000000 * 1e18; buyDevelopmentFee = _buyDevelopmentFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyDevelopmentFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellDevelopmentFee = _sellDevelopmentFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellDevelopmentFee + sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,235,540
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[emailΒ protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[emailΒ protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[emailΒ protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[emailΒ protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[emailΒ protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[emailΒ protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[emailΒ protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[emailΒ protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[emailΒ protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[emailΒ protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[emailΒ protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[emailΒ protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[emailΒ protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[emailΒ protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[emailΒ protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[emailΒ protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[emailΒ protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[emailΒ protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[emailΒ protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[emailΒ protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[emailΒ protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[emailΒ protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[emailΒ protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[emailΒ protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[emailΒ protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[emailΒ protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[emailΒ protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[emailΒ protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailΒ protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[emailΒ protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
Cancels the shares request of the caller Delete the request, start the cooldown period, and return the investment asset
function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); }
1,697,337
// SPDX-License-Identifier: MIT /* ======================================================= DEFI HUNTERS DAO ========================================================= https://defihuntersdao.club/ ------------------------------------------------------------ Feb 2021 --------------------------------------------------------------- NNNNNNNNL NNNNNNNNL .NNNN. .NNNNNNN. .JNNNNNN (NNNNNNNNNN JNNNL (NN) .NNNN NNN NNNNNNNNNN. NNNNNNNNNN. JNNNN) JNNNNNNNNNL NNNNNNNF (NNNNNNNNNN .NNNNN (NN) NNNN NNN NNN 4NNN NNN 4NNN NNNNNN (NNN` `NNN) (NNF NNN (NNNNN) (NN) NNNF .__ .___ ___..__ NNN NNN) NNN NNN) (NN)4NN) NNN) (NNN (NNN_ NNN NNN`NNN (NN)NNNF NNN (NNNNNNNN) JNNNNNNNN NNN 4NN) NNN 4NN) NNN (NNN NNN` `NNN 4NNNNN. NNN (NN) NNN) (NNNNNN. NNN (NNNF"NNNN (NNNF"NNNN NNN JNN) NNN JNN) (NNF NNN) NNN NNN "NNNNNN NNN NNN` (NNN (NNNNNNN NNN (NNF NNN NNN) NNN NNN NNN) NNN NNN) JNNNNNNNNL NNN) (NNN 4NNN) NNN .NNNNNNNNN. (NNN NNNL NNN (NN) NNN NNN NNN NNN JNNN NNN JNNN .NNNNNNNNNN 4NNN NNNF (NN) NNN JNNNNNNNNN) (NN) `NNN) NNN (NN) NNN NNN) .NNN NNN___NNNN` NNN___NNNN` (NNF NNN) NNNNL_JNNNN (NL__JNNN) NNN NNN` (NNN (NN) (NNN) NNN (NN) NNN (NNNNNNNNN NNNNNNNNN` NNNNNNNNN` NNN` (NNN 4NNNNNNNF (NNNNNNN) NNN (NNF NNN) (NN) (NNN.NNN (NN) NNN `NNNNNNNN """"""` """"""` """ """ """"" `""""` `""` `""` """ `""` """ .NNN NNNNNNNN) NNNNNNN` ================================================================================================================================ */ pragma solidity ^0.8.11; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IToken { function approve(address spender,uint256 amount)external; function allowance(address owner,address spender)external view returns(uint256); function balanceOf(address addr)external view returns(uint256); function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); } /** ΠšΠΎΠ½Ρ‚Ρ€Π°ΠΊΡ‚ стСйкинга Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² DDAO для участия Π² аллокациях ΠΈΠ»ΠΈ Π»ΡŽΠ±Ρ‹Ρ… ΠΈΠ½Ρ‹Ρ… мСроприятиях ΠΎΡ‚ https://defihuntersdao.club/ Для отраТСния всСй суммы стСйкинга Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΠΎ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ Ρ‚ΠΎΠΊΠ΅Π½Ρ‹ Π½Π°Ρ…ΠΎΠ΄ΠΈΠ»ΠΈΡΡŒ Π½Π° ΠΊΠΎΠ½Ρ‚Ρ€Π°ΠΊΡ‚Π΅ Π½Π΅ ΠΌΠ΅Π½Π΅Π΅ 5 Π΄Π½Π΅ΠΉ. ВывСсти Ρ‚ΠΎΠΊΠ΅Π½Ρ‹ ΠΌΠΎΠΆΠ½ΠΎ Π² любой ΠΌΠΎΠΌΠ΅Π½Ρ‚. **/ contract DDAOStaking01 is AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; address public owner = _msgSender(); /** Π‘Ρ‚ΡƒΠΊΡ‚ΡƒΡ€Π° хранСния Π΄Π°Π½Π½Ρ‹Ρ… ΠΎ ΠΊΠ°ΠΆΠ΄ΠΎΠΌ кошСлькС, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π΄Π΅Π»Π°Π΅Ρ‚ стСйк **/ struct info { bool exists; address addr; uint48 time; uint256 amount; uint256 stale; } mapping (address => info) public Stakers; address[] Users; /** Π’ стСйк ΠΎΡ‚Π΄Π°ΡŽΡ‚ΡΡ ΠΌΠΎΠ½Π΅Ρ‚Ρ‹ Π½Π° ΠΏΠ΅Ρ€ΠΈΠΎΠ΄ 5 Ρ€Π°Π· ΠΏΠΎ 1 дню ΠΈΠ·Π½Π°Ρ‡Π°Π»ΡŒΠ½ΠΎ. Π—Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ StakeTime ΠΌΠΎΠΆΠ΅Ρ‚ ΠΌΠ΅Π½ΡΡ‚ΡŒΡΡ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠ΅ΠΉ StakeTimeChang(). **/ uint48 public StakeTime = 1 hours; uint8 constant stake_steps = 5; // коэффициСнт округлСния. Π˜Π·Π½Π°Ρ‡Π°Π»ΡŒΠ½ΠΎ Π±Π΅Ρ€Π΅Ρ‚ΡŒΡΡ 0.1% uint16 constant koef = 1000; // DDAO TOken // testnet address public TokenAddr = 0xF870b9C48C2B9757696c25988426e2A0941334B5; // mainnet //address public TokenAddr = 0x90F3edc7D5298918F7BB51694134b07356F7d0C7; event eStake(address addr, uint256 amount, uint48 time, uint256 now_amount, uint256 stale); event eUnStake(address addr, uint256 amount, uint48 time, uint256 now_amount, uint256 stale); event eStakeStaleFix(address addr, uint48 time, uint256 now_amount, uint256 stale); constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); Admins.push(_msgSender()); //AdminAdd(_msgSender()); // Административный адрСс Π²Π»Π°Π΄Π΅Π»ΡŒΡ†Π° DDAO //_setupRole(DEFAULT_ADMIN_ROLE, 0x208b02f98d36983982eA9c0cdC6B3208e0f198A3); AdminAdd(0x208b02f98d36983982eA9c0cdC6B3208e0f198A3); //_setupRole(DEFAULT_ADMIN_ROLE, 0x80C01D52e55e5e870C43652891fb44D1810b28A2); } // Start: Admin functions event adminModify(string txt, address addr); address[] Admins; modifier onlyAdmin() { require(IsAdmin(_msgSender()), "Access for Admin's only"); _; } function IsAdmin(address account) public virtual view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, account); } function AdminAdd(address account) public virtual onlyAdmin { require(!IsAdmin(account),'Account already ADMIN'); grantRole(DEFAULT_ADMIN_ROLE, account); emit adminModify('Admin added',account); Admins.push(account); } function AdminDel(address account) public virtual onlyAdmin { require(IsAdmin(account),'Account not ADMIN'); require(_msgSender()!=account,'You can`t remove yourself'); revokeRole(DEFAULT_ADMIN_ROLE, account); emit adminModify('Admin deleted',account); } /** Бписок адрСсов, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΌΠΎΠ³ΡƒΡ‚ Π±Ρ‹Ρ‚ΡŒ Π°Π΄ΠΌΠΈΠ½Π°ΠΌΠΈ. ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΈΡ‚ΡŒ Π½ΡƒΠΆΠ½ΠΎ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ: IsAdmin(address) **/ function AdminList()public view returns(address[] memory) { return Admins; } // End: Admin functions function TokenAddrSet(address addr)public virtual onlyAdmin { TokenAddr = addr; } /** Tokens have already been sold to customers and they have received aDDAO. We answer with our name. In the last change, we added token addresses directly to the contract so that it would not be visible that these are not proxy contracts. The withdrawal of tokens is needed in case we are somehow broken, despite all the tests and audits, so that we can withdraw and redo the contract **/ function AdminGetCoin(uint256 amount) public onlyAdmin { payable(_msgSender()).transfer(amount); } function AdminGetToken(address tokenAddress, uint256 amount) public onlyAdmin { IERC20 ierc20Token = IERC20(tokenAddress); ierc20Token.safeTransfer(_msgSender(), amount); } /** Π’ Π±ΡƒΠ΄ΡƒΡ‰Π΅ΠΌ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΠ½Π°Π΄ΠΎΠ±ΠΈΡ‚ΡŒΡΡ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ΡŒ ΠΈΠ½Ρ‚Π΅Ρ€Π²Π°Π» стСйкинга **/ function StakeTimeChange(uint48 time)public onlyAdmin { StakeStaleMultiFix(); StakeTime = time; } /** функция Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ баланс Π² Ρ‚ΠΎΠΊΠ΅Π½Π°Ρ… DDAO ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΡƒΠΆΠ΅ ΠΎΡ‚Π»Π΅ΠΆΠ°Π»ΠΈΡΡŒ Π² стСйкингС (Π½Π΅ вСсь баланс Π² стСйкингС) Synonym balanceOf() - for compatibility discord services, allocation and others services **/ function StakeStale(address addr)public view returns(uint256 balance) { balance = Stakers[addr].stale.add(StakeCalculate(addr,0)); } function balanceOf(address addr)public view returns(uint256 balance) { balance = StakeStale(addr); } /** Ѐункция Π²Ρ‹Π²ΠΎΠ΄Π° всСго застСйканного баланса **/ function StakeAmount(address addr)public view returns(uint256 balance) { balance = Stakers[addr].stale.add(Stakers[addr].amount); } // Ѐункция Π²Ρ‹Π²ΠΎΠ΄Π° баланса Ρ‚ΠΎΠΊΠ΅Π½Π° DDAO для Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ ΠΊΠΎΠ½Ρ‚Ρ€Π°ΠΊΡ‚Π° function TokenBalance() public view returns(uint256) { IERC20 ierc20Token = IERC20(TokenAddr); return ierc20Token.balanceOf(address(this)); } // owner ddao and his friend /** Π’ стСйкинг ΠΌΠΎΠΆΠ΅Ρ‚ Π·Π°ΠΊΠΈΠ½ΡƒΡ‚ΡŒ любой адрСс. НСобходимо, Ρ‡Ρ‚ΠΎΠ±Ρ‹ Π½Π° балансС Π±Ρ‹Π»ΠΈ Ρ‚ΠΎΠΊΠ΅Π½Ρ‹. К ΠΏΡ€ΠΈΠΌΠ΅Ρ€Ρƒ, Ρƒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ Π΅ΡΡ‚ΡŒ горячий, Ρ…ΠΎΠ»ΠΎΠ΄Π½Ρ‹ΠΉ кошСлСк, Ledger, Trezor etc. Для упрощСния Ρ€Π°Π±ΠΎΡ‚Ρ‹ с Ρ‚ΠΎΠΊΠ΅Π½Π°ΠΌΠΈ для участия Π² сСйлах ΠΈΠ»ΠΈ Π΄Ρ€ΡƒΠ³ΠΈΡ… мСроприятиях ΠΎΡ‚ https://defihuntersdao.club/ ΠΌΠΎΠΆΠ½ΠΎ Π²Ρ‹ΠΏΠΎΠ»Π½ΡΡ‚ΡŒ дСйствия с ΠΎΠ΄Π½ΠΎΠ³ΠΎ адрСса, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Π½Π΅ ΠΊΠ°ΡΠ°ΡŽΡ‚ΡΡ снятия срСдств. !!! Π’Π°ΠΆΠ½ΠΎ: Если ΠΎΡ‚ΠΏΡ€Π°Π²ΠΈΡ‚Π΅Π»ΡŒ этой Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π΄Π΅Π»Π°Π΅Ρ‚ стСйк для адрСса, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π΅ΠΌΡƒ Π½Π΅ ΠΏΡ€ΠΈΠ½Π°Π΄Π»Π΅ΠΆΠΈΡ‚ - доступ ΠΊ Ρ‚ΠΎΠΊΠ΅Π½Π°ΠΌ тСряСтся навсСгда. **/ function Stake(address addr,uint256 amount)public { require(amount.mul(10**IToken(TokenAddr).decimals()) <= IERC20(TokenAddr).balanceOf(_msgSender()),"Not enough tokens to receive"); require(IERC20(TokenAddr).allowance(_msgSender(),address(this)) >= amount.mul(10**IToken(TokenAddr).decimals()),"You need to be allowed to use tokens to pay for this contract [We are wait approve]"); if(addr == address(0))addr = _msgSender(); IERC20(TokenAddr).safeTransferFrom(_msgSender(),address(this), amount.mul(10**IToken(TokenAddr).decimals())); if(Stakers[addr].time == 0) { Stakers[addr].time = uint48(block.timestamp); Stakers[addr].addr = addr; Stakers[addr].amount = amount; Stakers[addr].stale = 0; Users.push(addr); } else { //uint256 stale = StakeCalculate(addr,uint48(block.timestamp)); StakeStaleFix(addr); Stakers[addr].time = uint48(block.timestamp); Stakers[addr].amount = Stakers[addr].amount.add(amount); } emit eStake(addr, amount, Stakers[addr].time, Stakers[addr].amount, Stakers[addr].stale); } /** Ѐункция высчитываСт ΠΈ ΠΏΠΎΠΊΠ°Π·Ρ‹Π²Π°Π΅Ρ‚ суммы Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΌΠΎΠ³ΡƒΡ‚ ΡΡ‡ΠΈΡ‚Π°Ρ‚ΡŒΡΡ ΠΎΡ‚Π»Π΅ΠΆΠ°Π²ΡˆΠΈΠΌΠΈΡΡ Π² зависимости ΠΎΡ‚ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ. **/ function StakeCalculate(address addr,uint48 time)public view returns(uint256 stale) { if(time == 0)time = uint48(block.timestamp); uint48 interval; uint256 delta_amount; uint48 delta_time; uint256 part; interval = StakeTime * stake_steps; delta_amount = Stakers[addr].amount - Stakers[addr].stale; delta_time = time - Stakers[addr].time; part = delta_time * koef / interval; if(part > koef)part = koef; stale = Stakers[addr].amount * part / koef; } //only owner of ddao /** Π’Ρ‹Π²ΠΎΠ΄ Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² ΠΌΠΎΠΆΠ½ΠΎ ΠΎΡΡƒΡ‰Π΅ΡΡ‚Π²ΠΈΡ‚ΡŒ Π² любой ΠΌΠΎΠΌΠ΅Π½Ρ‚. Π’Ρ‹Π²ΠΎΠ΄ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΎΡΡƒΡ‰Π΅ΡΡ‚Π²ΠΈΡ‚ΡŒ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π²Π»Π°Π΄Π΅Π»Π΅Ρ† адрСса. **/ function Unstake(uint256 amount)public { address addr = _msgSender(); uint256 all = Stakers[addr].amount + Stakers[addr].stale; require(amount <= all,'You have requested more tokens than you have in the stake'); StakeStaleFix(addr); if(Stakers[addr].stale == 0) { Stakers[addr].amount = Stakers[addr].amount.sub(amount); } else { if(amount >= Stakers[addr].amount) { amount = amount.sub(Stakers[addr].amount); Stakers[addr].amount = 0; Stakers[addr].stale = Stakers[addr].stale.sub(amount); } else { Stakers[addr].amount = Stakers[addr].amount.sub(amount); } } Stakers[addr].time = uint48(block.timestamp); IERC20(TokenAddr).safeTransfer(_msgSender(), amount.mul(10**IToken(TokenAddr).decimals())); emit eUnStake(addr, amount, Stakers[addr].time, Stakers[addr].amount, Stakers[addr].stale); } /** Ѐункция фиксасции суммы ΠΎΡ‚Π»Π΅ΠΆΠ°Π²ΡˆΠΈΡ…ΡΡ Ρ‚ΠΎΠΊΠ΅Π½ΠΎΠ² ΠΈ свСТих Π² зависимости ΠΎΡ‚ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ. **/ function StakeStaleFix(address addr)public { if(Stakers[addr].amount >= 0) { uint256 temp; temp = StakeCalculate(addr,0); require(temp <= Stakers[addr].amount,"Unknown Error in StakeCalculate"); Stakers[addr].stale = Stakers[addr].stale.add(temp); Stakers[addr].amount = Stakers[addr].amount.sub(temp); Stakers[addr].time = uint48(block.timestamp); emit eStakeStaleFix(addr, Stakers[addr].time, Stakers[addr].amount, Stakers[addr].stale); } } /** Ѐункция пСрСсчСта ΠΎΡ‚Π»Π΅ΠΆΠ°Π²ΡˆΠΈΡ…ΡΡ сумм. НуТна ΠΏΡ€ΠΈ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΈ ΠΈΠ½Ρ‚Π΅Ρ€Π²Π°Π»Π°. **/ function StakeStaleMultiFix()public { for(uint32 i=0;i < Users.length;i++) { StakeStaleFix(Users[i]); } } /** Π˜Π½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡ ΠΎ Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΌ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ Π±Π»ΠΎΠΊΠ° Π² сСти **/ function BlockTime()public view returns(uint256) { return block.timestamp; } function StakersCount()public view returns(uint256) { return Users.length; } function StakersList()public view returns(address[] memory) { return Users; } }
Ѐункция Π²Ρ‹Π²ΠΎΠ΄Π° баланса Ρ‚ΠΎΠΊΠ΅Π½Π° DDAO для Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ ΠΊΠΎΠ½Ρ‚Ρ€Π°ΠΊΡ‚Π°
function TokenBalance() public view returns(uint256) { IERC20 ierc20Token = IERC20(TokenAddr); return ierc20Token.balanceOf(address(this)); } К ΠΏΡ€ΠΈΠΌΠ΅Ρ€Ρƒ, Ρƒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ Π΅ΡΡ‚ΡŒ горячий, Ρ…ΠΎΠ»ΠΎΠ΄Π½Ρ‹ΠΉ кошСлСк, Ledger, Trezor etc. ΠΌΠΎΠΆΠ½ΠΎ Π²Ρ‹ΠΏΠΎΠ»Π½ΡΡ‚ΡŒ дСйствия с ΠΎΠ΄Π½ΠΎΠ³ΠΎ адрСса, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Π½Π΅ ΠΊΠ°ΡΠ°ΡŽΡ‚ΡΡ снятия срСдств. !!! Π’Π°ΠΆΠ½ΠΎ: Если ΠΎΡ‚ΠΏΡ€Π°Π²ΠΈΡ‚Π΅Π»ΡŒ этой Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π΄Π΅Π»Π°Π΅Ρ‚ стСйк для адрСса, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π΅ΠΌΡƒ Π½Π΅ ΠΏΡ€ΠΈΠ½Π°Π΄Π»Π΅ΠΆΠΈΡ‚ - доступ ΠΊ Ρ‚ΠΎΠΊΠ΅Π½Π°ΠΌ тСряСтся навсСгда.
12,788,527
./partial_match/1/0xA46A84212Dd030Fec09081d83B587a5F57aB81dB/sources/GenerationalPepe.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Generational Pepe", "GEPE") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 15; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 25; uint256 totalSupply = 42069000000 * 1e18; maxTransactionAmount = totalSupply * 20 / 1000; maxWallet = totalSupply * 20 / 1000; swapTokensAtAmount = totalSupply * 5 / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); devWallet = address(owner()); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,006,256
./partial_match/1/0xFC634bfc0f00A2D3dCc93CeB4558Da9DE840fdBC/sources/MetaLifeOgPets.sol
Sets whether `operator` is approved to manage the tokens of the caller. Emits a {ApprovalForAll} event. @solidity memory-safe-assembly Convert to 0 or 1. Update the `isApproved` for (`msg.sender`, `operator`). Emit the {ApprovalForAll} event.
function setApprovalForAll(address operator, bool isApproved) public virtual { assembly { isApproved := iszero(iszero(isApproved)) mstore(0x1c, operator) mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x30), isApproved) mstore(0x00, isApproved) log3( 0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)) ) } }
9,237,479
./full_match/1/0x70C65C7b4B52A61d9FE6eE46Be0a3D1f23B53450/sources/contracts/ERC20CompetitiveRewardModule.sol
private helper method for funding with fee processing/ get fees do funding
function _fund( address token, uint256 amount, uint256 duration, uint256 start ) private { _update(); (address receiver, uint256 rate) = _config.getAddressUint96( keccak256("gysr.core.competitive.fund.fee") ); _fund(token, amount, duration, start, receiver, rate); }
3,072,888
pragma solidity ^0.5.0; import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol"; contract User { using SafeMath for uint256; address contractOwner = msg.sender; enum userStates {pending, active, deactivated, admin} uint256 public numberOfUsers = 0; struct user { uint256 userId; address userWallet; string about; string displayPictureHash; string displayName; string website; userStates state; } user[] public users; mapping(address => bool) public userExists; mapping(address => uint256) public userIds; event UserCreated( uint256 userId, address userWallet, string about, string displayPictureHash, string displayName, string website ); event UserAboutChanged(address userWallet, string about); event UserDisplayPictureChanged( address userWallet, string displayPictureHash ); event UserDisplayNameChanged(address userWallet, string displayName); event UserWebsiteChanged(address userWallet, string website); event UserActivated(address userWallet); event UserDeactivated(address userWallet); event UserNewAdmin(address userWallet); /** * Ensures a unique user address is supplied */ modifier uniqueUser(address _userWallet) { require(!userExists[_userWallet], "User already exists!"); _; } /** * Ensures that meme owner is the one modifying meme contents */ modifier isUser(address _userWallet) { require( tx.origin == _userWallet, "You must be the User of your own profile" ); _; } /** * Ensures that function caller is an admin */ modifier isAdmin() { require( checkUserIsAdmin(tx.origin), "You must be an admin to call this function" ); _; } /** * Creates a default admin account */ constructor() public { //Create admin user createUser( msg.sender, "I am the boss", "QmP1KdPrFV9wKbDy5WvCDKd3YcyTBbFvqfvBCzjGrDiVLZ", "BigPepeBoss", "www.4chan.org" ); users[userIds[msg.sender]].state = userStates.admin; } function getContractOwner() public returns (address) { return contractOwner; } /** * Creates a new user with supplied variables * Requirements: * - `_userwallet` supplied must be user's own address */ function createUser( address _userWallet, string memory _about, string memory _displayPictureHash, string memory _displayName, string memory _website ) public isUser(_userWallet) uniqueUser(_userWallet) { user memory newUser = user( numberOfUsers, _userWallet, _about, _displayPictureHash, _displayName, _website, userStates.pending ); users.push(newUser); emit UserCreated( numberOfUsers, _userWallet, _about, _displayPictureHash, _displayName, _website ); userExists[_userWallet] = true; userIds[_userWallet] = numberOfUsers; numberOfUsers = numberOfUsers.add(1); } /** * Update User's about description * Requirements: * - User calling this function has to be owner of user profile */ function setUserAbout(address _userWallet, string memory _about) public isUser(_userWallet) { users[userIds[_userWallet]].about = _about; emit UserAboutChanged(_userWallet, _about); } /** * Update User's Display Picture * Requirements: * - User calling this function has to be owner of user profile */ function setUserDisplayPicture( address _userWallet, string memory _displayPictureHash ) public isUser(_userWallet) { users[userIds[_userWallet]].displayPictureHash = _displayPictureHash; emit UserDisplayPictureChanged(_userWallet, _displayPictureHash); } /** * Update User's display name * Requirements: * - User calling this function has to be owner of user profile */ function setUserDisplayName(address _userWallet, string memory _displayName) public isUser(_userWallet) { users[userIds[_userWallet]].displayName = _displayName; emit UserDisplayNameChanged(_userWallet, _displayName); } /** * Update User's website * Requirements: * - User calling this function has to be owner of user profile */ function setUserWebsite(address _userWallet, string memory _website) public isUser(_userWallet) { users[userIds[_userWallet]].website = _website; emit UserWebsiteChanged(_userWallet, _website); } /** * Deactivate User * Requirements: * - User calling this function has to be an admin */ function setUserAsDeactivated(address _userWallet) public isAdmin() { users[userIds[_userWallet]].state = userStates.deactivated; emit UserDeactivated(_userWallet); } /** * Activate User * Requirements: * - User calling this function has to be an admin */ function setUserAsActive(address _userWallet) public isAdmin() { users[userIds[_userWallet]].state = userStates.active; emit UserActivated(_userWallet); } /** * Set user as admin * Requirements: * - User calling this function has to be an admin */ function setUserAsAdmin(address _userWallet) public isAdmin() { users[userIds[_userWallet]].state = userStates.admin; emit UserNewAdmin(_userWallet); } /** * developers: Checks if a supplied `_userWallet` exists */ function checkUserExists(address _userWallet) public view returns (bool) { return userExists[_userWallet]; } /** * developers: Checks if a supplied `_userWallet` is an admin */ function checkUserIsAdmin(address _userWallet) public view returns (bool) { return users[userIds[_userWallet]].state == userStates.admin; } /** * Checks if a supplied `_userWallet` is active */ function checkUserIsActive(address _userWallet) public view returns (bool) { return users[userIds[_userWallet]].state == userStates.active; } /** * Checks if a supplied `_userWallet` is pending */ function checkUserIsPending(address _userWallet) public view returns (bool) { return users[userIds[_userWallet]].state == userStates.pending; } /** * Returns total number of registered users */ function getNumberUsers() public view returns (uint256) { return numberOfUsers; } /** * Returns a User Address given a supplied index `i` * Requirements: * - Supplied index `i` must be a valid index */ function getUserAddress(uint256 i) public view returns (address) { require(i < numberOfUsers, "Not a valid User ID"); return users[i].userWallet; } }
Deactivate User Requirements: - User calling this function has to be an admin/
function setUserAsDeactivated(address _userWallet) public isAdmin() { users[userIds[_userWallet]].state = userStates.deactivated; emit UserDeactivated(_userWallet); }
1,789,271
import "./IStrategy.sol"; import "./Pool.sol"; import "./openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; import "./openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; contract justStoreItStrategy is IStrategy{ IERC20 Coin; Pool MyPool; constructor(address coin, address pool) { Coin = IERC20(coin); MyPool = Pool(pool); } function deposit(uint256 amount) external override{ } function loseMoney(uint256 amount) external{ Coin.transfer(msg.sender, amount); } // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256 amount) external override{ require(msg.sender == address(MyPool), "only pool can withdraw funds"); Coin.transfer(address(MyPool), amount); } // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external override returns (uint256){ require(msg.sender == address(MyPool), "only pool can withdraw funds"); Coin.transfer(address(MyPool), Coin.balanceOf(address(this))); } //returns total balance of all funds in the strategy in some number forms that corresponds to the underlying strategy //should have the users balance in strategy be proportional to their ownership of the pool's liquidity function totalBalance() external view override returns (uint256){ return Coin.balanceOf(address(this)); } }
Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256 amount) external override{ require(msg.sender == address(MyPool), "only pool can withdraw funds"); Coin.transfer(address(MyPool), amount); }
15,802,775
pragma solidity ^0.5.17; contract ZCrypto { using SafeMath for uint256; string private _tokenName; string private _tokenSymbol; uint8 private _decimals; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; address private _minterAddress; address private _owner; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor () public { _owner = msg.sender; _tokenName = "ZCrypto"; _tokenSymbol = "ZCO"; _decimals = 8; uint256 initialSupply=10000000000000000; _minterAddress = _owner; address masterAccount= _owner; _totalSupply = _totalSupply.add(initialSupply); _balances[masterAccount] = _balances[masterAccount].add(initialSupply); emit Transfer(address(0), masterAccount, initialSupply); } //Returns the name of the token function name() public view returns (string memory) { return _tokenName; } //Returns the symbol of the token function symbol() public view returns (string memory) { return _tokenSymbol; } /** Returns the number of decimals the token uses - e.g. 8, means to divide the token amount by 100000000 to get its user representation. */ function decimals() public view returns (uint8) { return _decimals; } /** * returns total tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * returns the account balance of the specified address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * Returns the amount which spender is still allowed to withdraw from owner */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** *Transfer token for a specified address *Transfers tokens to address receiver, and MUST fire the Transfer event. *The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend. */ function transfer(address receiver, uint256 numTokens) public returns (bool) { _transfer(msg.sender, receiver, numTokens); return true; } /** * Allows spender to withdraw from your account msg.sender multiple times, up to the numTokens amount. * If this function is called again it overwrites the current allowance with numTokens. * Beware that changing an allowance with this method brings the risk that someone may use both the old * To prevent attack vectors like the one https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/ , * clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender. * THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before */ function approve(address spender, uint256 numTokens) public returns (bool) { _approve(msg.sender, spender, numTokens); emit Approval(msg.sender, spender, numTokens); return true; } /** * Transfer tokens from one address to another. */ function transferFrom(address from, address to, uint256 numTokens) public returns (bool) { _transfer(from, to, numTokens); _approve(from, msg.sender, _allowed[from][msg.sender].sub(numTokens)); return true; } /** * Transfer token from to a specified addresses */ function _transfer(address from, address to, uint256 numTokens) internal { require(to != address(0)); require(numTokens <= _balances[from]); _balances[from] = _balances[from].sub(numTokens); _balances[to] = _balances[to].add(numTokens); emit Transfer(from, to, numTokens); } /** * Approve an address to spend another addresses' tokens. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; } /** * Function to print new tokens */ function mint(address account, uint256 numTokens) public onlyMinter { require(account != address(0)); _totalSupply = _totalSupply.add(numTokens); _balances[account] = _balances[account].add(numTokens); emit Transfer(address(0), account, numTokens); } /** * @return the address that can mint tokens. */ function currentMinter() external view returns (address) { return _minterAddress; } /** * change minter address, newMinter The address that will be able to mint tokens from now on */ function changeMinter(address newMinter) external onlyOwner { _minterAddress = newMinter; } modifier onlyMinter() { require(msg.sender==_minterAddress); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "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 Returns the address of the current owner. */ function owner() public view returns (address) { return _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) external onlyOwner { if (newOwner != address(0)) { _owner = newOwner; } } } library SafeMath { /** * 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 ans = a - b; return ans; } /** * Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 ans = a + b; require(ans >= a); return ans; } }
Returns true if the caller is the current owner./
function isOwner() public view returns (bool) { return msg.sender == _owner; }
12,248,710
pragma solidity ^0.4.18; contract BlockSSL { struct certificateInfo { address creator; string uPortID; string certificateHash; uint serialNumber; uint expiry; } mapping (address => certificateInfo) certificates; address[] public certAdd; event certificateInfoAdded(address creator, string uPortID, string certificateHash, uint serialNumber, uint expiry); function setCertificate(address _address, address _creator, string _uPortID, string _certificateHash, uint _serialNumber, uint _expiry) public { var certificatesInfo = certificates[_address]; certificatesInfo.creator = _creator; certificatesInfo.uPortID = _uPortID; certificatesInfo.certificateHash = _certificateHash; certificatesInfo.serialNumber = _serialNumber; certificatesInfo.expiry = _expiry; certAdd.push(_address) -1; certificateInfoAdded(_creator, _uPortID, _certificateHash, _serialNumber, _expiry); } function getCertificatesInfo() view public returns (address[]) { //Get all the info that has been added return certAdd; } function getCertificateInfo(address cert) view public returns (address, string, string, uint, uint) { //Get info of a specified address return (certificates[cert].creator, certificates[cert].uPortID, certificates[cert].certificateHash, certificates[cert].serialNumber, certificates[cert].expiry); } function countCertificates() view public returns (uint){ //Count how many users create certificates return certAdd.length; } }
Get info of a specified address
function getCertificateInfo(address cert) view public returns (address, string, string, uint, uint) {
897,970
pragma solidity 0.8.2; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ /** * @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); } } } } 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"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } 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; } } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; // keccak256("InterestValidator"); bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _liquidator() internal view returns (address) { return nexus.getModule(KEY_LIQUIDATOR); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } } 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; } } abstract contract AbstractIntegration is IPlatformIntegration, Initializable, ImmutableModule, ReentrancyGuard { event PTokenAdded(address indexed _bAsset, address _pToken); event Deposit(address indexed _bAsset, address _pToken, uint256 _amount); event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount); event PlatformWithdrawal( address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount ); // LP has write access address public immutable lpAddress; // bAsset => pToken (Platform Specific Token Address) mapping(address => address) public override bAssetToPToken; // Full list of all bAssets supported here address[] internal bAssetsMapped; /** * @param _nexus Address of the Nexus * @param _lp Address of LP */ constructor(address _nexus, address _lp) ReentrancyGuard() ImmutableModule(_nexus) { require(_lp != address(0), "Invalid LP address"); lpAddress = _lp; } /** * @dev Simple initializer to set first bAsset/pTokens */ function initialize(address[] calldata _bAssets, address[] calldata _pTokens) public initializer { uint256 len = _bAssets.length; require(len == _pTokens.length, "Invalid inputs"); for (uint256 i = 0; i < len; i++) { _setPTokenAddress(_bAssets[i], _pTokens[i]); } } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyLP() { require(msg.sender == lpAddress, "Only the LP can execute"); _; } /*************************************** CONFIG ****************************************/ /** * @dev Provide support for bAsset by passing its pToken address. * This method can only be called by the system Governor * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _bAsset, address _pToken) external onlyGovernor { _setPTokenAddress(_bAsset, _pToken); } /** * @dev Provide support for bAsset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _bAsset, address _pToken) internal { require(bAssetToPToken[_bAsset] == address(0), "pToken already set"); require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses"); bAssetToPToken[_bAsset] = _pToken; bAssetsMapped.push(_bAsset); emit PTokenAdded(_bAsset, _pToken); _abstractSetPToken(_bAsset, _pToken); } function _abstractSetPToken(address _bAsset, address _pToken) internal virtual; /** * @dev Simple helper func to get the min of two values */ function _min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } interface ICERC20 { /** * @notice The mint function transfers an asset into the protocol, which begins accumulating * interest based on the current Supply Rate for the asset. The user receives a quantity of * cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate. * @param mintAmount The amount of the asset to be supplied, in units of the underlying asset. * @return 0 on success, otherwise an Error codes */ function mint(uint mintAmount) external returns (uint); /** * @notice The redeem underlying function converts cTokens into a specified quantity of the underlying * asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of * underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less * than the user's Account Liquidity and the market's available liquidity. * @param redeemAmount The amount of underlying to be redeemed. * @return 0 on success, otherwise an Error codes */ function redeemUnderlying(uint redeemAmount) external returns (uint); /** * @notice The user's underlying balance, representing their assets in the protocol, is equal to * the user's cToken balance multiplied by the Exchange Rate. * @param owner The account to get the underlying balance of. * @return The amount of underlying currently owned by the account. */ function balanceOfUnderlying(address owner) external returns (uint); /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() external view returns (uint); /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later /** * @title CompoundIntegration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Compound and Cream * @dev VERSION: 1.0 * DATE: 2021-05-04 */ contract CompoundIntegration is AbstractIntegration { using SafeERC20 for IERC20; event SkippedWithdrawal(address bAsset, uint256 amount); event RewardTokenApproved(address rewardToken, address account); address public immutable rewardToken; /** * @param _nexus Address of the Nexus * @param _lp Address of liquidity provider. eg mAsset or feeder pool * @param _rewardToken Reward token, if any. eg COMP */ constructor( address _nexus, address _lp, address _rewardToken ) AbstractIntegration(_nexus, _lp) { rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address is zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited cTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); // Get the Target token ICERC20 cToken = _getCTokenFor(_bAsset); quantityDeposited = _amount; if(isTokenFeeCharged) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(cToken); require(cToken.mint(_amount) == 0, "cToken mint failed"); uint256 newBal = _checkBalance(cToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { // Else just execute the mint require(cToken.mint(_amount) == 0, "cToken mint failed"); } emit Deposit(_bAsset, address(cToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from Compound * @param _receiver Address to which the withdrawn bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from Compound * @param _receiver Address to which the withdrawn bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); // Get the Target token ICERC20 cToken = _getCTokenFor(_bAsset); // If redeeming 0 cTokens, just skip, else COMP will revert // Reason for skipping: to ensure that redeemMasset is always able to execute uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _totalAmount); if(cTokensToRedeem == 0) { emit SkippedWithdrawal(_bAsset, _totalAmount); return; } uint256 userWithdrawal = _amount; if(_hasTxFee) { require(_amount == _totalAmount, "Cache inactive with tx fee"); IERC20 b = IERC20(_bAsset); uint256 prevBal = b.balanceOf(address(this)); require(cToken.redeemUnderlying(_amount) == 0, "redeem failed"); uint256 newBal = b.balanceOf(address(this)); userWithdrawal = _min(userWithdrawal, newBal - prevBal); } else { // Redeem Underlying bAsset amount require(cToken.redeemUnderlying(_totalAmount) == 0, "redeem failed"); } // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, userWithdrawal); emit PlatformWithdrawal(_bAsset, address(cToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Compound exchange rate between the cToken and bAsset gradually increases, * causing the cToken to be worth more corresponding bAsset. * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external override view returns (uint256 balance) { // balance is always with token cToken decimals ICERC20 cToken = _getCTokenFor(_bAsset); balance = _checkBalance(cToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Re-approve the spending of all bAssets by their corresponding cToken, * if for some reason is it necessary. Only callable through Governance. */ function reApproveAllTokens() external onlyGovernor { uint256 bAssetCount = bAssetsMapped.length; for(uint i = 0; i < bAssetCount; i++){ address bAsset = bAssetsMapped[i]; address cToken = bAssetToPToken[bAsset]; MassetHelpers.safeInfiniteApprove(bAsset, cToken); } } /** * @dev Internal method to respond to the addition of new bAsset / cTokens * We need to approve the cToken and give it permission to spend the bAsset * @param _bAsset Address of the bAsset to approve * @param _cToken This cToken has the approval approval */ function _abstractSetPToken(address _bAsset, address _cToken) internal override { // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, _cToken); } /*************************************** HELPERS ****************************************/ /** * @dev Get the cToken wrapped in the ICERC20 interface for this bAsset. * Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return cToken Corresponding cToken to this bAsset */ function _getCTokenFor(address _bAsset) internal view returns (ICERC20 cToken) { address cTokenAddress = bAssetToPToken[_bAsset]; require(cTokenAddress != address(0), "cToken does not exist"); cToken = ICERC20(cTokenAddress); } /** * @dev Get the total bAsset value held in the platform * underlying = (cTokenAmt * exchangeRate) / 1e18 * @param _cToken cToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(ICERC20 _cToken) internal view returns (uint256 balance) { uint256 cTokenBalance = _cToken.balanceOf(address(this)); uint256 exchangeRate = _cToken.exchangeRateStored(); // e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18 balance = (cTokenBalance * exchangeRate) / 1e18; } /** * @dev Converts an underlying amount into cToken amount * cTokenAmt = (underlying * 1e18) / exchangeRate * @param _cToken cToken for which to change * @param _underlying Amount of underlying to convert * @return amount Equivalent amount of cTokens */ function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying) internal view returns (uint256 amount) { uint256 exchangeRate = _cToken.exchangeRateStored(); // e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8 // e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0 amount = (_underlying * 1e18) / exchangeRate; } }
Re-approve the spending of all bAssets by their corresponding cToken, if for some reason is it necessary. Only callable through Governance./
function reApproveAllTokens() external onlyGovernor { uint256 bAssetCount = bAssetsMapped.length; for(uint i = 0; i < bAssetCount; i++){ address bAsset = bAssetsMapped[i]; address cToken = bAssetToPToken[bAsset]; MassetHelpers.safeInfiniteApprove(bAsset, cToken); } }
220,740
./partial_match/1/0xE3AfFe3c4ae73e5a0BAa1306EC4b79d95Ba770d6/sources/HushProtocol.sol
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) { require(_allowances[sender][msg.sender] >= amount, "ERC20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount); return true; }
2,704,394
pragma solidity ^0.4.24; import "./../../ModuleFactory.sol"; import "./LockupVolumeRestrictionTM.sol"; /** * @title Factory for deploying ManualApprovalTransferManager module */ contract LockupVolumeRestrictionTMFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { version = "1.0.0"; name = "LockupVolumeRestrictionTM"; title = "Lockup Volume Restriction Transfer Manager"; description = "Manage transfers using lock ups over time"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); } /** * @notice Used to launch the Module with the help of factory * @return address Contract address of the Module */ function deploy(bytes /* _data */) external returns(address) { if (setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided"); LockupVolumeRestrictionTM lockupVolumeRestrictionTransferManager = new LockupVolumeRestrictionTM(msg.sender, address(polyToken)); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(address(lockupVolumeRestrictionTransferManager), getName(), address(this), msg.sender, now); return address(lockupVolumeRestrictionTransferManager); } /** * @notice Type of the Module factory * @return uint8 */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 2; return res; } /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns(string) { return "Allows an issuer to set lockup periods for user addresses, with funds distributed over time. Init function takes no parameters."; } /** * @notice Get the tags related to the module factory */ function getTags() external view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](2); availableTags[0] = "Volume"; availableTags[1] = "Transfer Restriction"; return availableTags; } }
Get the tags related to the module factory/
function getTags() external view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](2); availableTags[0] = "Volume"; availableTags[1] = "Transfer Restriction"; return availableTags; }
881,525
./full_match/44787/0x5089cB9AFD321f97601c834A2280D04CE95E7411/sources/contracts/MarketPlaceNom.sol
See {INFTKEYMarketPlaceV1-enterBidForToken}. People can only enter bid if bid is allowed The timestamp set needs to be in the allowed range bid price > 0 must not be token owner must allow this contract to spend enough payment token/
function enterBidForToken( address sender, string memory name, uint256 bidPrice ) external payable{ uint256 tokenId = calculateTokenId(name); require(bidPrice > 0, "Please bid for more than 0"); require(!_isTokenOwner(tokenId, sender), "This Token belongs to this address"); uint256 price = msg.value; if(isEtherToken() == false){ sendERC20(msg.sender, address(this), bidPrice); price = bidPrice; } Bid memory bid = Bid(tokenId, bidPrice, sender); if (!_tokenIdWithBid.contains(tokenId)) { _tokenIdWithBid.add(tokenId); } _tokenBids[tokenId].bidders.add(sender); _tokenBids[tokenId].bids[sender] = bid; }
13,273,304
./partial_match/4/0xD3aA9066B58c4C622a2367644f5813ef2868E3d6/sources/Implementation.sol
==================== bonds logic ======================= bonds can only be bought under 1USDC burn dollar from account
function purchaseBonds(uint256 dollarAmount) external returns (uint256) { uint256 epoch = epoch(); (Decimal.D256 memory price, Decimal.D256 memory redeemablePrice, uint256 bondPremium) = epochPrice(epoch); Require.that( price.lessThan(Decimal.one()), FILE, "TWAP not below 1U" ); Require.that( dollarAmount > 0, FILE, "Must purchase none-zero amount" ); uint256 bondAmount = dollarAmount.add(bondPremium); dollar().transferFrom(msg.sender, address(this), dollarAmount); dollar().burn(dollarAmount); balanceCheck(); incrementBalanceOfBonds(msg.sender, epoch, bondAmount); emit BondPurchase(msg.sender, epoch, dollarAmount, bondAmount, bondPremium, redeemablePrice.value); return bondAmount; }
8,515,598
./partial_match/1/0xe37bb96500478285acE5F9F13f9d96dcbB10F263/sources/contracts/MorningsLimitedEditions.flatten.sol
Get the base NFT id from a token id Returns the token id argument if it's not an edition tokenId The token id for the edition return baseId The base NFT id e.g. 2 from "2004"/
function getEditionBaseIdFromTokenId(uint256 tokenId) external pure returns (uint256) { if (tokenId >= MAX_EDITION_SIZE) return tokenId; return tokenId / MAX_EDITION_SIZE; } ------------------------------------------------------------------------ */
16,029,759
./full_match/1/0x1bDfE04bB0Ef85047BA3e1Ce35f2649d8246F809/sources/contracts/PoxiMarketplaceV1.sol
Method for buying listed NFT _nftAddress NFT contract address _tokenId TokenId
function buyItem( address _nftAddress, uint256 _tokenId, address _payToken, address _owner ) external nonReentrant isListed(_nftAddress, _tokenId, _owner) validListing(_nftAddress, _tokenId, _owner) { Listing memory listedItem = listings[_nftAddress][_tokenId][_owner]; require(listedItem.payToken == _payToken, "Invalid pay token"); _buyItem(_nftAddress, _tokenId, _payToken, _owner); }
16,470,466
pragma solidity ^0.4.11; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint 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; } /** * Based on http://www.codecodex.com/wiki/Calculate_an_integer_square_root */ function sqrt(uint num) internal returns (uint) { if (0 == num) { // Avoid zero divide return 0; } uint n = (num / 2) + 1; // Initial estimate, never low uint n1 = (n + (num / n)) / 2; while (n1 < n) { n = n1; n1 = (n + (num / n)) / 2; } return n; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint 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, uint _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 uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @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 => uint)) 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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _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, uint _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 uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Crypto Masters Token * */ contract CryptoMastersToken is StandardToken { // metadata string public constant name = "Crypto Masters Token"; string public constant symbol = "CMT"; uint public constant decimals = 0; // crowdsale parameters uint public constant tokenCreationMin = 1000000; uint public constant tokenPriceMin = 0.0004 ether; // contructor parameters address public owner1; address public owner2; // contract state uint public EthersRaised = 0; bool public isHalted = false; // events event LogBuy(address indexed who, uint tokens, uint EthersValue, uint supplyAfter); /** * @dev Throws if called by any account other than one of the owners. */ modifier onlyOwner() { if (msg.sender != owner1 && msg.sender != owner2) { throw; } _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner1 The address to transfer ownership to. */ function transferOwnership1(address newOwner1) onlyOwner { require(newOwner1 != address(0)); owner1 = newOwner1; } function transferOwnership2(address newOwner2) onlyOwner { require(newOwner2 != address(0)); owner2 = newOwner2; } // constructor function CryptoMastersToken() { owner1 = msg.sender; owner2 = msg.sender; } /** * @dev Calculates how many tokens one can buy for specified value * @return Amount of tokens one will receive and purchase value without remainder. */ function getBuyPrice(uint _bidValue) constant returns (uint tokenCount, uint purchaseValue) { // Token price formula is twofold. We have flat pricing below tokenCreationMin, // and above that price linarly increases with supply. uint flatTokenCount; uint startSupply; uint linearBidValue; if(totalSupply < tokenCreationMin) { uint maxFlatTokenCount = _bidValue.div(tokenPriceMin); // entire purchase in flat pricing if(totalSupply.add(maxFlatTokenCount) <= tokenCreationMin) { return (maxFlatTokenCount, maxFlatTokenCount.mul(tokenPriceMin)); } flatTokenCount = tokenCreationMin.sub(totalSupply); linearBidValue = _bidValue.sub(flatTokenCount.mul(tokenPriceMin)); startSupply = tokenCreationMin; } else { flatTokenCount = 0; linearBidValue = _bidValue; startSupply = totalSupply; } // Solves quadratic equation to calculate maximum token count that can be purchased uint currentPrice = tokenPriceMin.mul(startSupply).div(tokenCreationMin); uint delta = (2 * startSupply).mul(2 * startSupply).add(linearBidValue.mul(4 * 1 * 2 * startSupply).div(currentPrice)); uint linearTokenCount = delta.sqrt().sub(2 * startSupply).div(2); uint linearAvgPrice = currentPrice.add((startSupply+linearTokenCount+1).mul(tokenPriceMin).div(tokenCreationMin)).div(2); // double check to eliminate rounding errors linearTokenCount = linearBidValue / linearAvgPrice; linearAvgPrice = currentPrice.add((startSupply+linearTokenCount+1).mul(tokenPriceMin).div(tokenCreationMin)).div(2); purchaseValue = linearTokenCount.mul(linearAvgPrice).add(flatTokenCount.mul(tokenPriceMin)); return ( flatTokenCount + linearTokenCount, purchaseValue ); } /** * Default function called by sending Ether to this address with no arguments. * */ function() payable { BuyLimit(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /** * @dev Buy tokens */ function Buy() payable external { BuyLimit(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /** * @dev Buy tokens with limit maximum average price * @param _maxPrice Maximum price user want to pay for one token */ function BuyLimit(uint _maxPrice) payable public { require(msg.value >= tokenPriceMin); assert(!isHalted); uint boughtTokens; uint averagePrice; uint purchaseValue; (boughtTokens, purchaseValue) = getBuyPrice(msg.value); if(boughtTokens == 0) { // bid to small, return ether and abort msg.sender.transfer(msg.value); return; } averagePrice = purchaseValue.div(boughtTokens); if(averagePrice > _maxPrice) { // price too high, return ether and abort msg.sender.transfer(msg.value); return; } assert(averagePrice >= tokenPriceMin); assert(purchaseValue <= msg.value); totalSupply = totalSupply.add(boughtTokens); balances[msg.sender] = balances[msg.sender].add(boughtTokens); LogBuy(msg.sender, boughtTokens, purchaseValue.div(1000000000000000000), totalSupply); if(msg.value > purchaseValue) { msg.sender.transfer(msg.value.sub(purchaseValue)); } EthersRaised += purchaseValue.div(1000000000000000000); } /** * @dev Withdraw funds to owners. */ function withdrawAllFunds() external onlyOwner { msg.sender.transfer(this.balance); } function withdrawFunds(uint _amount) external onlyOwner { require(_amount <= this.balance); msg.sender.transfer(_amount); } /** * * @dev When contract is halted no one can buy new tokens. * */ function haltCrowdsale() external onlyOwner { isHalted = !isHalted; } }
Default function called by sending Ether to this address with no arguments./
function() payable { BuyLimit(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); }
934,799
./full_match/97/0x8D20eDbd0179be99a6605D893969aeb442A0BE61/sources/contracts/periphery/PrizeTierHistory.sol
@inheritdoc IPrizeTierHistory
function getPrizeTierList(uint32[] calldata _drawIds) external view override returns (PrizeTier[] memory) { PrizeTier[] memory _data = new PrizeTier[](_drawIds.length); for (uint256 index = 0; index < _drawIds.length; index++) { } return _data; }
5,044,299
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/PLBTStaking/IPLBTStaking.sol"; import "./interfaces/DAO/IDAO.sol"; import "./sushiswap/IUniswapV2Router02.sol"; import "./gysr/ERC20FriendlyRewardModule.sol"; import "./gysr/PoolFactory.sol"; import "./gysr/interfaces/IPool.sol"; ///@title DAO contract contract DAO is IDAO, AccessControl { using SafeERC20 for IERC20; /// status of vote enum Decision { none, votedFor, votedAgainst } /// type of proposal types enum ChangesType { none, strategy, allocation, quorum, majority, treasury, cancel } /// state of proposal enum Status { none, proposal, finished, voting } /// struct represents a vote struct Vote { // amount of tokens in vote uint256 amount; // voting decision Decision decision; } /// struct for storing proposal struct Voting { // voting id uint256 id; // in support of votes uint256 votesFor; // against votes uint256 votesAgainst; // when started uint256 startTime; // voting may execute only after voting ended uint256 endTime; // this time increases if this voting is being cancelled uint256 finishTime; // time when changes come in power uint256 implementationTime; // creator address address creator; // address of proposal creator ChangesType changesType; // proposal status Status status; // indicator showing if proposal was cancelled bool wasCancelled; // bytecode to run on the finishvote bytes data; } /// represents allocation percentage struct Allocation { uint8 plbtStakers; uint8 osomStakers; uint8 lpStakers; uint8 buyback; } /// represents amount of tokens in percentage put on investing strategies struct Strategy { uint8 autopilot; uint8 uniswap; uint8 aave; uint8 anchor; } ///@dev emmited when new proposal created ///@param creator address of proposal creator ///@param key hash passed to event in order to match with backend, for storing proposal descriptions ///@param id id of proposal ///@param startTime time when voting on proposal starts ///@param endTime time when voting on proposal ends event ProposalAdded( address indexed creator, bytes32 key, uint256 indexed id, uint256 startTime, uint256 endTime ); ///@dev emmited when proposal transitioned to main voting status ///@param id id of proposal ///@param startTime time when main voting starts ///@param endTime time when main voting ends event VotingBegan(uint256 indexed id, uint256 startTime, uint256 endTime); ///@dev emmited when voting is finished ///@param id id of finished proposal ///@param executed shows if finish was successfully executed ///@param votesFor with how many tokens voted for proposal ///@param votesAgainst with how many tokens voted against proposal event Finished( uint256 indexed id, bool indexed executed, uint256 votesFor, uint256 votesAgainst ); ///@dev emmited when someone voted on proposal ///@param voter address of voter ///@param id id of proposal ///@param decision shows if voted for or against ///@param amount amount of tokens voted with event CastedOnProposal( address indexed voter, uint256 indexed id, bool decision, uint256 amount ); ///@dev emmited when someone voted in main voting ///@param voter address of voter ///@param id id of proposal ///@param decision shows if voted for or against ///@param amount amount of tokens voted with event CastedOnVoting( address indexed voter, uint256 indexed id, bool decision, uint256 amount ); ///@dev modifier used for restricted function execution modifier onlyDAO() { require( msg.sender == address(this), "DAO: only dao can call this function." ); _; } /// role of treasury holder bytes32 public TREASURY_ROLE = keccak256("TREASURY_ROLE"); /// threshold for proposal to pass uint256 public proposalMajority; ///threshold for voting to pass uint256 public votingMajority; /// threshold for proposal to become valid uint256 public proposalQuorum; /// threshold for voting to become valid uint256 public votingQuorum; /// debating period duration uint256 public votingPeriod; /// voting count uint256 public votingsCount; /// regular timelock uint256 public regularTimelock; /// cancel timelock uint256 public cancelTimelock; /// Allocation Allocation public allocation; /// Strategy Strategy public strategy; /// Treasury owner address treasury; /// for percent calculations uint256 private precision = 1e6; /// staking contracts IPLBTStaking private staking; /// tokens IERC20 private plbt; IERC20 private weth; IERC20 private wbtc; /// Router IUniswapV2Router02 router; ///pool address address public pool; ///GYSR Pool address public gysr; ///OSOM address address OSOM; ///array of function selectors bytes4[6] selectors = [ this.changeStrategy.selector, this.changeAllocation.selector, this.changeQuorum.selector, this.changeMajority.selector, this.changeTreasury.selector, this.cancelVoting.selector ]; /// active proposals uint256[10] public proposals; /// initialized bool private initialized; mapping(uint256 => Voting) public votings; /// storing votes from a certain address for voting mapping(uint256 => mapping(address => Vote)) public votingDecisions; /// current voting uint256 public activeVoting; /// current cancel uint256 public activeCancellation; ///@param _proposalMajority initial percent of proposal majority of votes to become valid ///@param _votingMajority initial percent of main voting majority of votes to become valid ///@param _proposalQuorum initial percent of proposal quorum ///@param _votingQuorum initial percent of main voting quorum ///@param _votingPeriod initial voting period time ///@param _regularTimelock initial timelock period ///@param _cancelTimelock initial cancel timelock period ///@param _allocation initial allocation config ///@param _strategy initial strategy config constructor( uint256 _proposalMajority, uint256 _votingMajority, uint256 _proposalQuorum, uint256 _votingQuorum, uint256 _votingPeriod, uint256 _regularTimelock, uint256 _cancelTimelock, Allocation memory _allocation, Strategy memory _strategy ) { proposalMajority = _proposalMajority; votingMajority = _votingMajority; proposalQuorum = _proposalQuorum; votingQuorum = _votingQuorum; votingPeriod = _votingPeriod; regularTimelock = _regularTimelock; cancelTimelock = _cancelTimelock; allocation = _allocation; strategy = _strategy; _setupRole(DEFAULT_ADMIN_ROLE, address(this)); _setRoleAdmin(TREASURY_ROLE, DEFAULT_ADMIN_ROLE); } ///@dev initializing DAO with settings ///@param _router SushiSwap router address ///@param _treasury address of the treasury holder ///@param _stakingAddr address of staking ///@param _plbt Polybius token address ///@param _weth address of wEth ///@param _wbtc address of wBTC ///@param _poolFactory address of GYSR pool factory ///@param _stakingFactory address of GYSR staking module Factory ///@param _rewardFactory address of GYSR reward module factory ///@param _slpAddress address of PLBT-wETH LP token address ///@param _OSOM address of OSOM function initialize( address _router, address _treasury, address _stakingAddr, address _plbt, address _weth, address _wbtc, address _poolFactory, address _stakingFactory, address _rewardFactory, address _slpAddress, address _OSOM ) external { require(!initialized, "DAO: Already initialized."); treasury = _treasury; _setupRole(TREASURY_ROLE, treasury); staking = IPLBTStaking(_stakingAddr); plbt = IERC20(_plbt); weth = IERC20(_weth); wbtc = IERC20(_wbtc); PoolFactory factory = PoolFactory(_poolFactory); bytes memory stakingdata = (abi.encode(_slpAddress)); bytes memory rewarddata = (abi.encode(_plbt, 10**18, 2592000)); pool = factory.create( _stakingFactory, _rewardFactory, stakingdata, rewarddata ); gysr = IPool(pool).rewardModule(); OSOM = _OSOM; router = IUniswapV2Router02(_router); _setupRole(TREASURY_ROLE, treasury); initialized = true; } ///@dev distributing fund to parties and staking contracts, and buying back PLBT from Sushiswap pool ///@param toStakersWETH amount of wETH to distribute to PLBTStakers ///@param toStakersWBTC amount of wBTC to distribute to PLBTStakers ///@param toLPStakers amount of PLBT to distribute to LPStakers on GYSR ///@param toOSOMWETH amount of wETH to distribute to PLBTStakers on OSOM ///@param toOSOMWBTC amount of wBTC to distribute to PLBTStakers on OSOM ///@param toBuyback amount of wETH to swap for PLBT function distribute( uint256 toStakersWETH, uint256 toStakersWBTC, uint256 toLPStakers, uint256 toOSOMWETH, uint256 toOSOMWBTC, uint256 toBuyback ) external onlyRole(TREASURY_ROLE) { if (toStakersWETH != 0 && toStakersWBTC != 0) { weth.safeTransferFrom(treasury, address(staking), toStakersWETH); wbtc.safeTransferFrom(treasury, address(staking), toStakersWBTC); staking.setReward(toStakersWETH, toStakersWBTC); } if (toLPStakers != 0) { plbt.safeTransferFrom(treasury, address(this), toLPStakers); plbt.approve(gysr, toLPStakers); ERC20FriendlyRewardModule(gysr).fund(toLPStakers, 2592000); } if (toOSOMWETH != 0 && toOSOMWBTC != 0) { weth.safeTransferFrom(treasury, OSOM, toOSOMWETH); wbtc.safeTransferFrom(treasury, OSOM, toOSOMWBTC); } if (toBuyback != 0) { uint256 total = plbt.balanceOf(address(this)); weth.safeTransferFrom(treasury, address(this), toBuyback); address[] memory path = new address[](2); path[0] = address(weth); path[1] = address(plbt); uint256[] memory amounts = router.getAmountsOut(toBuyback, path); weth.approve(address(router), amounts[0]); router.swapTokensForExactTokens( amounts[1], amounts[0], path, address(this), block.timestamp + 600 ); uint256 current = plbt.balanceOf(address(this)); uint256 burn = current - total; plbt.safeTransfer(address(0), burn); } } function changeOSOM(address _address) external onlyRole(TREASURY_ROLE) { require(_address != address(0), "DAO: can't set zero-address"); OSOM = _address; } ///@dev function which matches function selector with bytecode ///@param _changesType shows which function selector is expected ///@param _data bytecode to match modifier matchChangesTypes(ChangesType _changesType, bytes memory _data) { require( _changesType != ChangesType.none, "DAO: addProposal bad arguments." ); bytes4 outBytes4; assembly { outBytes4 := mload(add(_data, 0x20)) } require( outBytes4 == selectors[uint256(_changesType) - 1], "DAO: bytecode is wrong" ); _; } ///@dev function which will be called on Finish; changes proposal or main voting quorums ///@param or shows what quorum to change ///@param _quorum new quorum percent value function changeQuorum(bool or, uint256 _quorum) public onlyDAO { or ? votingQuorum = _quorum : proposalQuorum = _quorum; } ///@dev function which will be called on Finish; changes proposal or main voting Majority ///@param or shows what Majority to change ///@param _majority new Majority percent value function changeMajority(bool or, uint256 _majority) public onlyDAO { or ? votingMajority = _majority : proposalMajority = _majority; } ///@dev function which will be called on Finish of cancellation voting ///@param id id of main voting function cancelVoting(uint256 id) public onlyDAO { votings[id].status = Status.finished; } ///@dev function which will be called on Finish; changes allocation parameters ///@param _allocation new allocation config function changeAllocation(Allocation memory _allocation) public onlyDAO { allocation = _allocation; } ///@dev function which will be called on Finish; changes strategy parameters ///@param _strategy new strategy config function changeStrategy(Strategy memory _strategy) public onlyDAO { strategy = _strategy; } ///@dev function which will be called on Finish; changes treasury holder address ///@param _treasury new treasury holder address function changeTreasury(address _treasury) public onlyDAO { revokeRole(TREASURY_ROLE, treasury); treasury = _treasury; grantRole(TREASURY_ROLE, treasury); staking.changeTreasury(_treasury); } ///@dev check if proposal passed quorum and majority thresholds ///@param proposal proposal sent to validate function validate(Voting memory proposal) private view returns (bool) { uint256 total = proposal.votesFor + proposal.votesAgainst; if (total == 0) { return false; } bool quorum; uint256 supply = plbt.totalSupply() - plbt.balanceOf(address(0)); bool majority; if (proposal.status == Status.voting) { quorum = ((total * precision) / supply) > votingQuorum; majority = (proposal.votesFor * precision) / total > votingMajority; } else { quorum = ((total * precision) / supply) > proposalQuorum; majority = (proposal.votesFor * precision) / total > proposalMajority; } return majority && quorum; } ///@dev picks next proposal out of proposal pool function pickProposal() private view returns (uint256 id, bool check) { if (votings[activeVoting].status == Status.voting) { return (0, false); } uint256 temp = 0; Voting memory proposal; for (uint256 i = 0; i < proposals.length; i++) { proposal = votings[proposals[i]]; if (proposal.status == Status.proposal && validate(proposal)) { (temp == 0 || proposal.startTime < votings[temp].startTime) ? temp = proposal.id : 0; } } if (temp != 0 && validate(votings[temp])) { return (temp, true); } return (0, false); } ///@dev send proposal to main voting round ///@param id id of proposal function sendProposalToVoting(uint256 id) private { Voting storage proposal = votings[id]; proposal.status = Status.voting; proposal.startTime = block.timestamp; proposal.endTime = block.timestamp + votingPeriod; proposal.finishTime = proposal.endTime + regularTimelock; activeVoting = id; emit VotingBegan(proposal.id, proposal.startTime, proposal.endTime); } ///@dev adds proposal to proposal pool ///@param _changesType type of proposal ///@param _data executable bytecode to execute on Finish ///@param id key for matching frontend request with this contract logs function addProposal( ChangesType _changesType, bytes memory _data, bytes32 id ) public matchChangesTypes(_changesType, _data) { bool cancel = _changesType == ChangesType.cancel; require( !(cancel && votings[activeCancellation].status == Status.voting), "Cancel Voting already exists" ); if (cancel) { Voting storage voting = votings[activeVoting]; require( voting.wasCancelled == false && voting.status == Status.voting, "DAO: Can't cancel twice." ); require( voting.endTime < block.timestamp && voting.finishTime > block.timestamp, "DAO: can only cancel during timelock" ); voting.finishTime = block.timestamp + cancelTimelock; voting.wasCancelled = true; } votingsCount++; Voting memory proposal = Voting({ id: votingsCount, votesFor: 0, votesAgainst: 0, startTime: block.timestamp, endTime: block.timestamp + votingPeriod, finishTime: 0, implementationTime: 0, creator: msg.sender, changesType: _changesType, status: Status.proposal, wasCancelled: false, data: _data }); votings[votingsCount] = proposal; if (cancel) { activeCancellation = votingsCount; votings[activeCancellation].status = Status.voting; votings[activeCancellation].finishTime = votings[activeCancellation] .endTime; emit ProposalAdded( msg.sender, id, votingsCount, proposal.startTime, proposal.endTime ); return; } bool proposalAdded = false; bool check; for (uint256 i = 0; i < proposals.length; i++) { if ( votings[proposals[i]].status != Status.proposal || proposals[i] == 0 ) { check = true; } else { if ( votings[proposals[i]].endTime <= block.timestamp && votings[proposals[i]].status == Status.proposal ) { check = !(validate(votings[proposals[i]])); } } if (check) { proposals[i] = proposal.id; proposalAdded = true; break; } } require(proposalAdded, "DAO: proposals list is full"); emit ProposalAdded( msg.sender, id, votingsCount, proposal.startTime, proposal.endTime ); } ///@dev participate in main voting round ///@param id id of proposal ///@param amount amount of tokens to vote with ///@param decision shows if voted for or against function participateInVoting( uint256 id, uint256 amount, bool decision ) external { // check if proposal is active bool check = votings[id].status == Status.voting && votings[id].endTime >= block.timestamp; require(check, "DAO: voting ended"); // check if voted Vote storage vote = votingDecisions[id][msg.sender]; require( vote.decision == Decision.none && vote.amount == 0, "DAO: you have already voted" ); // check if msg.sender has available tokens uint256 possible = getAvailableTokens(msg.sender); require(amount > 0 && amount <= possible, "DAO: incorrect amount"); Voting storage voting = votings[id]; vote.amount += amount; if (decision) { voting.votesFor += amount; vote.decision = Decision.votedFor; } else { voting.votesAgainst += amount; vote.decision = Decision.votedAgainst; } emit CastedOnVoting(msg.sender, id, decision, amount); } ///@dev participate in proposal ///@param id id of proposal ///@param amount amount of tokens to vote with ///@param decision shows if voted for or against function participateInProposal( uint256 id, uint256 amount, bool decision ) external { // check if proposal is active bool check = votings[id].status == Status.proposal && votings[id].endTime >= block.timestamp; require(check, "DAO: proposal ended"); // check if voted Voting storage proposal = votings[id]; Vote storage vote = votingDecisions[proposal.id][msg.sender]; require( vote.decision == Decision.none && vote.amount == 0, "DAO: you have already voted" ); // check if msg.sender has available tokens uint256 possible = getAvailableTokens(msg.sender); require(amount > 0 && amount <= possible, "DAO: incorrect amount"); vote.amount += amount; if (decision) { proposal.votesFor += amount; vote.decision = Decision.votedFor; } else { proposal.votesAgainst += amount; vote.decision = Decision.votedAgainst; } votings[proposal.id] = proposal; (uint256 picked, bool found) = pickProposal(); if (found) { sendProposalToVoting(picked); } emit CastedOnProposal(msg.sender, id, decision, amount); } ///@dev to finish main voting round and run changes on success ///@param id id of proposal to finish function finishVoting(uint256 id) public { Voting storage voting = votings[id]; require( (voting.status == Status.voting), "DAO: the result of the vote has already been completed," ); require( block.timestamp > (voting.finishTime), "DAO: Voting can't be finished yet." ); bool result = validate(voting); if (result && voting.changesType != ChangesType.cancel) { (bool success, ) = address(this).call{value: 0}(voting.data); voting.implementationTime = block.timestamp; } if (voting.changesType == ChangesType.cancel) { if (result) { address(this).call{value: 0}(voting.data); } else { bytes memory data = voting.data; uint256 id_; assembly { let sig := mload(add(data, add(4, 0))) id_ := mload(add(data, 36)) } votings[id_].finishTime = votings[id_].endTime; finishVoting(id_); } } voting.status = Status.finished; (uint256 picked, bool found) = pickProposal(); if (found) { sendProposalToVoting(picked); } emit Finished(id, result, voting.votesFor, voting.votesAgainst); } ///@dev used for situations, when previously passed proposal wasn't finished and proposal pool is full ///@param finishId id of proposal to finish ///@param _changesType type of proposal ///@param _data executable bytecode to execute on Finish ///@param id key for matching frontend request with this contract logs function finishAndAddProposal( uint256 finishId, ChangesType _changesType, bytes calldata _data, bytes32 id ) external { finishVoting(finishId); addProposal(_changesType, _data, id); } ///@dev get all locked tokens for address `staker`, so user cannot unstake or vote with tokens used in proposals ///@param staker address of staker function getLockedTokens(address staker) public view override returns (uint256 locked) { for (uint256 i = 0; i < proposals.length; i++) { if ( (votings[proposals[i]].endTime > block.timestamp || validate(votings[proposals[i]])) && votings[proposals[i]].status == Status.proposal ) locked += votingDecisions[proposals[i]][staker].amount; } if ( votings[activeVoting].status == Status.voting && votings[activeVoting].finishTime > block.timestamp ) { locked += votingDecisions[activeVoting][staker].amount; } if ( votings[activeCancellation].status == Status.voting && votings[activeCancellation].finishTime > block.timestamp ) { locked += votingDecisions[activeCancellation][staker].amount; } return locked; } ///@dev get available tokens for address `staker`, so user cannot unstake or vote with tokens used in proposals ///@param staker address of staker function getAvailableTokens(address staker) public view override returns (uint256 available) { uint256 locked = getLockedTokens(staker); uint256 staked = staking.getStakedTokens(staker); available = staked - locked; return available; } ///@dev returns all proposals from pool function getAllProposals() external view returns (Voting[] memory) { Voting[] memory proposalsList = new Voting[](10); // allocate array memory for (uint256 i = 0; i < proposals.length; i++) { { proposalsList[i] = votings[proposals[i]]; } } return proposalsList; } ///@dev returns all votings ///@return array of proposals from pool function getAllVotings() external view returns (Voting[] memory) { Voting[] memory votingsList = new Voting[](votingsCount); // allocate array memory for (uint256 i = 0; i < votingsCount; i++) { { votingsList[i] = votings[i + 1]; } } return votingsList; } ///@dev returns proposal info with additional information for frontend ///@return proposal struct ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveVoting() external view returns ( Voting memory, uint256 creatorAmountStaked, uint256, uint256 ) { creatorAmountStaked = staking.getStakedTokens( votings[activeVoting].creator ); return ( votings[activeVoting], creatorAmountStaked, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@return proposal struct ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveCancellation() external view returns ( Voting memory, uint256 creatorAmountStaked, uint256, uint256 ) { creatorAmountStaked = staking.getStakedTokens( votings[activeCancellation].creator ); return ( votings[activeCancellation], creatorAmountStaked, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param user address of the user ///@return proposal struct ///@return vote struct ///@return available amount of available for voting tokens by `user` ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveVoting(address user) external view returns ( Voting memory, Vote memory, uint256 available, uint256 creatorAmountStaked, uint256, uint256 ) { available = getAvailableTokens(user); creatorAmountStaked = staking.getStakedTokens( votings[activeVoting].creator ); return ( votings[activeVoting], votingDecisions[activeVoting][user], creatorAmountStaked, available, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param user address of the user ///@return proposal struct ///@return vote struct ///@return available amount of available for voting tokens by `user` ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getActiveCancellation(address user) external view returns ( Voting memory, Vote memory, uint256 available, uint256 creatorAmountStaked, uint256, uint256 ) { available = getAvailableTokens(user); creatorAmountStaked = staking.getStakedTokens( votings[activeCancellation].creator ); return ( votings[activeCancellation], votingDecisions[activeCancellation][user], creatorAmountStaked, available, votingQuorum, votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param id id of proposal ///@return proposal struct ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getProposalInfo(uint256 id) external view returns ( Voting memory, uint256 creatorAmountStaked, uint256, uint256 ) { creatorAmountStaked = staking.getStakedTokens(votings[id].creator); return ( votings[id], creatorAmountStaked, votings[id].status == Status.proposal ? proposalQuorum : votingQuorum, votings[id].status == Status.proposal ? proposalMajority : votingMajority ); } ///@dev returns proposal info with additional information for frontend ///@param id id of proposal ///@param user address of the user ///@return proposal struct ///@return vote struct ///@return available amount of available for voting tokens by `user` ///@return creatorAmountStaked amount of staked tokens by proposal creator ///@return quorum ///@return majority function getProposalInfo(uint256 id, address user) external view returns ( Voting memory, Vote memory, uint256 available, uint256 creatorAmountStaked, uint256, uint256 ) { available = getAvailableTokens(user); creatorAmountStaked = staking.getStakedTokens(votings[id].creator); return ( votings[id], votingDecisions[id][user], creatorAmountStaked, available, votings[id].status == Status.proposal ? proposalQuorum : votingQuorum, votings[id].status == Status.proposal ? proposalMajority : votingMajority ); } ///@dev returns DAO configuration parameters ///@return allocation config ///@return strategy config ///@return proposal majority ///@return main voting round majority ///@return proposal quorum ///@return main voting round quorum function InfoDAO() external view returns ( Allocation memory, Strategy memory, uint256, uint256, uint256, uint256 ) { return ( allocation, strategy, proposalMajority, votingMajority, proposalQuorum, votingQuorum ); } } // 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; /** * @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.4; ///@title Interface for PLBTSTaking contract for DAO interactions interface IPLBTStaking { ///@dev returns amount of staked tokens by user `_address` ///@param _address address of the user ///@return amount of tokens function getStakedTokens(address _address) external view returns (uint256); ///@dev sets reward for next distribution time ///@param _amountWETH amount of wETH tokens ///@param _amountWBTC amount of wBTC tokens function setReward(uint256 _amountWETH, uint256 _amountWBTC) external; ///@dev changes treasury address ///@param _treasury address of the treasury function changeTreasury(address _treasury) external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; interface IDAO { function getLockedTokens(address staker) external view returns(uint256 locked); function getAvailableTokens(address staker) external view returns(uint256 locked); } // SPDX-License-Identifier: GPL-3.0 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; } /* ERC20FriendlyRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "./interfaces/IRewardModule.sol"; import "./interfaces/IEvents.sol"; import "./ERC20BaseRewardModule.sol"; import "./GysrUtils.sol"; /** * @title ERC20 friendly reward module * * @notice this reward module distributes a single ERC20 token as the staking reward. * It is designed to offer simple and predictable reward mechanics. * * @dev rewards are immutable once earned, and can be claimed by the user at * any time. The module can be configured with a linear vesting schedule to * incentivize longer term staking. The user can spend GYSR at the time of * staking to receive a multiplier on their earning rate. */ contract ERC20FriendlyRewardModule is ERC20BaseRewardModule { using GysrUtils for uint256; // constants uint256 public constant FULL_VESTING = 10**DECIMALS; // single stake by user struct Stake { uint256 shares; uint256 gysr; uint256 bonus; uint256 rewardTally; uint256 timestamp; } // mapping of user to all of their stakes mapping(address => Stake[]) public stakes; // total shares without GYSR multiplier applied uint256 public totalRawStakingShares; // total shares with GYSR multiplier applied uint256 public totalStakingShares; // counter representing the current rate of rewards per share uint256 public rewardsPerStakedShare; // value to keep track of earnings to be put back into the pool uint256 public rewardDust; // timestamp of last update uint256 public lastUpdated; // minimum ratio of earned rewards measured against FULL_VESTING (i.e. 2.5 * 10^17 would be 25%) uint256 public immutable vestingStart; // length of time in seconds until the user receives a FULL_VESTING (1x) multiplier on rewards uint256 public immutable vestingPeriod; IERC20 private immutable _token; address private immutable _factory; /** * @param token_ the token that will be rewarded * @param vestingStart_ minimum ratio earned * @param vestingPeriod_ period (in seconds) over which investors vest to 100% * @param factory_ address of module factory */ constructor( address token_, uint256 vestingStart_, uint256 vestingPeriod_, address factory_ ) { require(vestingStart_ <= FULL_VESTING, "frm1"); _token = IERC20(token_); _factory = factory_; vestingStart = vestingStart_; vestingPeriod = vestingPeriod_; lastUpdated = block.timestamp; } /** * @inheritdoc IRewardModule */ function tokens() external view override returns (address[] memory tokens_) { tokens_ = new address[](1); tokens_[0] = address(_token); } /** * @inheritdoc IRewardModule */ function factory() external view override returns (address) { return _factory; } /** * @inheritdoc IRewardModule */ function balances() external view override returns (uint256[] memory balances_) { balances_ = new uint256[](1); balances_[0] = totalLocked(); } /** * @inheritdoc IRewardModule */ function usage() external view override returns (uint256) { return _usage(); } /** * @inheritdoc IRewardModule */ function stake( address account, address user, uint256 shares, bytes calldata data ) external override onlyOwner returns (uint256, uint256) { _update(); return _stake(account, user, shares, data); } /** * @notice internal implementation of stake method * @param account address of staking account * @param user address of user * @param shares number of new shares minted * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function _stake( address account, address user, uint256 shares, bytes calldata data ) internal returns (uint256, uint256) { require(data.length == 0 || data.length == 32, "frm2"); uint256 gysr; if (data.length == 32) { assembly { gysr := calldataload(164) } } uint256 bonus = gysr.gysrBonus(shares, totalRawStakingShares + shares, _usage()); if (gysr > 0) { emit GysrSpent(user, gysr); } // update user staking info stakes[account].push( Stake(shares, gysr, bonus, rewardsPerStakedShare, block.timestamp) ); // add new shares to global totals totalRawStakingShares += shares; totalStakingShares += (shares * bonus) / 10**DECIMALS; return (gysr, 0); } /** * @inheritdoc IRewardModule */ function unstake( address account, address user, uint256 shares, bytes calldata ) external override onlyOwner returns (uint256, uint256) { _update(); return _unstake(account, user, shares); } /** * @notice internal implementation of unstake * @param account address of staking account * @param user address of user * @param shares number of shares burned * @return amount of gysr spent * @return amount of gysr vested */ function _unstake( address account, address user, uint256 shares ) internal returns (uint256, uint256) { // redeem first-in-last-out uint256 sharesLeftToBurn = shares; Stake[] storage userStakes = stakes[account]; uint256 rewardAmount; uint256 gysrVested; uint256 preVestingRewards; uint256 timeVestingCoeff; while (sharesLeftToBurn > 0) { Stake storage lastStake = userStakes[userStakes.length - 1]; if (lastStake.shares <= sharesLeftToBurn) { // fully redeem a past stake preVestingRewards = _rewardForStakedShares( lastStake.shares, lastStake.bonus, lastStake.rewardTally ); timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp); rewardAmount += (preVestingRewards * timeVestingCoeff) / 10**DECIMALS; rewardDust += (preVestingRewards * (FULL_VESTING - timeVestingCoeff)) / 10**DECIMALS; totalStakingShares -= (lastStake.shares * lastStake.bonus) / 10**DECIMALS; sharesLeftToBurn -= lastStake.shares; gysrVested += lastStake.gysr; userStakes.pop(); } else { // partially redeem a past stake preVestingRewards = _rewardForStakedShares( sharesLeftToBurn, lastStake.bonus, lastStake.rewardTally ); timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp); rewardAmount += (preVestingRewards * timeVestingCoeff) / 10**DECIMALS; rewardDust += (preVestingRewards * (FULL_VESTING - timeVestingCoeff)) / 10**DECIMALS; totalStakingShares -= (sharesLeftToBurn * lastStake.bonus) / 10**DECIMALS; uint256 partialVested = (sharesLeftToBurn * lastStake.gysr) / lastStake.shares; gysrVested += partialVested; lastStake.shares -= sharesLeftToBurn; lastStake.gysr -= partialVested; sharesLeftToBurn = 0; } } // update global totals totalRawStakingShares -= shares; if (rewardAmount > 0) { _distribute(user, address(_token), rewardAmount); } if (gysrVested > 0) { emit GysrVested(user, gysrVested); } return (0, gysrVested); } /** * @inheritdoc IRewardModule */ function claim( address account, address user, uint256 shares, bytes calldata data ) external override onlyOwner returns (uint256 spent, uint256 vested) { _update(); (, vested) = _unstake(account, user, shares); (spent, ) = _stake(account, user, shares, data); } /** * @dev compute rewards owed for a specific stake * @param shares number of shares to calculate rewards for * @param bonus associated bonus for this stake * @param rewardTally associated rewardTally for this stake * @return reward for these staked shares */ function _rewardForStakedShares( uint256 shares, uint256 bonus, uint256 rewardTally ) internal view returns (uint256) { return ((((rewardsPerStakedShare - rewardTally) * shares) / 10**DECIMALS) * // counteract rewardsPerStakedShare coefficient bonus) / 10**DECIMALS; // counteract bonus coefficient } /** * @notice compute vesting multiplier as function of staking time * @param time epoch time at which the tokens were staked * @return vesting multiplier rewards */ function timeVestingCoefficient(uint256 time) public view returns (uint256) { if (vestingPeriod == 0) return FULL_VESTING; uint256 stakeTime = block.timestamp - time; if (stakeTime > vestingPeriod) return FULL_VESTING; return vestingStart + (stakeTime * (FULL_VESTING - vestingStart)) / vestingPeriod; } /** * @inheritdoc IRewardModule */ function update(address) external override { requireOwner(); _update(); } /** * @notice method called ad hoc to clean up and perform additional accounting * @dev will only be called manually, and should not contain any essential logic */ function clean() external override { requireOwner(); _update(); _clean(address(_token)); } /** * @notice fund Geyser by locking up reward tokens for distribution * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked */ function fund(uint256 amount, uint256 duration) external { _update(); _fund(address(_token), amount, duration, block.timestamp); } /** * @notice fund Geyser by locking up reward tokens for distribution * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked * @param start time (seconds) at which funding begins to unlock */ function fund( uint256 amount, uint256 duration, uint256 start ) external { _update(); _fund(address(_token), amount, duration, start); } /** * @dev updates the internal accounting for rewards per staked share * retrieves unlocked tokens and adds on any unvested rewards from the last unstake operation */ function _update() private { lastUpdated = block.timestamp; if (totalStakingShares == 0) { rewardsPerStakedShare = 0; return; } uint256 rewardsToUnlock = _unlockTokens(address(_token)) + rewardDust; rewardDust = 0; // global accounting rewardsPerStakedShare += (rewardsToUnlock * 10**DECIMALS) / totalStakingShares; } /** * @return total number of locked reward tokens */ function totalLocked() public view returns (uint256) { if (lockedShares(address(_token)) == 0) { return 0; } return (_token.balanceOf(address(this)) * lockedShares(address(_token))) / totalShares(address(_token)); } /** * @return total number of unlocked reward tokens */ function totalUnlocked() public view returns (uint256) { uint256 unlockedShares = totalShares(address(_token)) - lockedShares(address(_token)); if (unlockedShares == 0) { return 0; } return (_token.balanceOf(address(this)) * unlockedShares) / totalShares(address(_token)); } /** * @dev internal helper to get current usage ratio * @return GYSR usage ratio */ function _usage() private view returns (uint256) { if (totalStakingShares == 0) { return 0; } return ((totalStakingShares - totalRawStakingShares) * 10**DECIMALS) / totalStakingShares; } /** * @param addr address of interest * @return number of active stakes for user */ function stakeCount(address addr) public view returns (uint256) { return stakes[addr].length; } } /* PoolFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IModuleFactory.sol"; import "./interfaces/IStakingModule.sol"; import "./interfaces/IRewardModule.sol"; import "./OwnerController.sol"; import "./Pool.sol"; /** * @title Pool factory * * @notice this implements the Pool factory contract which allows any user to * easily configure and deploy their own Pool * * @dev it relies on a system of sub-factories which are responsible for the * creation of underlying staking and reward modules. This primary factory * calls each module factory and assembles the overall Pool contract. * * this contract also manages various privileged platform settings including * treasury address, fee amount, and module factory whitelist. */ contract PoolFactory is IPoolFactory, OwnerController { // events event PoolCreated(address indexed user, address pool); event FeeUpdated(uint256 previous, uint256 updated); event TreasuryUpdated(address previous, address updated); event WhitelistUpdated( address indexed factory, uint256 previous, uint256 updated ); // types enum ModuleFactoryType {Unknown, Staking, Reward} // constants uint256 public constant MAX_FEE = 20 * 10**16; // 20% // fields mapping(address => bool) public map; address[] public list; address private _gysr; address private _treasury; uint256 private _fee; mapping(address => ModuleFactoryType) public whitelist; /** * @param gysr_ address of GYSR token */ constructor(address gysr_, address treasury_) { _gysr = gysr_; _treasury = treasury_; _fee = MAX_FEE; } /** * @notice create a new Pool * @param staking address of factory that will be used to create staking module * @param reward address of factory that will be used to create reward module * @param stakingdata construction data for staking module factory * @param rewarddata construction data for reward module factory * @return address of newly created Pool */ function create( address staking, address reward, bytes calldata stakingdata, bytes calldata rewarddata ) external returns (address) { // validate require(whitelist[staking] == ModuleFactoryType.Staking, "f1"); require(whitelist[reward] == ModuleFactoryType.Reward, "f2"); // create modules address stakingModule = IModuleFactory(staking).createModule(stakingdata); address rewardModule = IModuleFactory(reward).createModule(rewarddata); // create pool Pool pool = new Pool(stakingModule, rewardModule, _gysr, address(this)); // set access IStakingModule(stakingModule).transferOwnership(address(pool)); IRewardModule(rewardModule).transferOwnership(address(pool)); pool.transferControl(msg.sender); // this also sets controller for modules pool.transferOwnership(msg.sender); // bookkeeping map[address(pool)] = true; list.push(address(pool)); // output emit PoolCreated(msg.sender, address(pool)); return address(pool); } /** * @inheritdoc IPoolFactory */ function treasury() external view override returns (address) { return _treasury; } /** * @inheritdoc IPoolFactory */ function fee() external view override returns (uint256) { return _fee; } /** * @notice update the GYSR treasury address * @param treasury_ new value for treasury address */ function setTreasury(address treasury_) external { requireController(); emit TreasuryUpdated(_treasury, treasury_); _treasury = treasury_; } /** * @notice update the global GYSR spending fee * @param fee_ new value for GYSR spending fee */ function setFee(uint256 fee_) external { requireController(); require(fee_ <= MAX_FEE, "f3"); emit FeeUpdated(_fee, fee_); _fee = fee_; } /** * @notice set the whitelist status of a module factory * @param factory_ address of module factory * @param type_ updated whitelist status for module */ function setWhitelist(address factory_, uint256 type_) external { requireController(); require(type_ <= uint256(ModuleFactoryType.Reward), "f4"); require(factory_ != address(0), "f5"); emit WhitelistUpdated(factory_, uint256(whitelist[factory_]), type_); whitelist[factory_] = ModuleFactoryType(type_); } /** * @return total number of Pools created by the factory */ function count() public view returns (uint256) { return list.length; } } /* IPool https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Pool interface * * @notice this defines the core Pool contract interface */ interface IPool { /** * @return staking tokens for Pool */ function stakingTokens() external view returns (address[] memory); /** * @return reward tokens for Pool */ function rewardTokens() external view returns (address[] memory); /** * @return staking balances for user */ function stakingBalances(address user) external view returns (uint256[] memory); /** * @return total staking balances for Pool */ function stakingTotals() external view returns (uint256[] memory); /** * @return reward balances for Pool */ function rewardBalances() external view returns (uint256[] memory); /** * @return GYSR usage ratio for Pool */ function usage() external view returns (uint256); /** * @return address of staking module */ function stakingModule() external view returns (address); /** * @return address of reward module */ function rewardModule() external view returns (address); /** * @notice stake asset and begin earning rewards * @param amount number of tokens to unstake * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function stake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice unstake asset and claim rewards * @param amount number of tokens to unstake * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function unstake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice claim rewards without unstaking * @param amount number of tokens to claim against * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function claim( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice method called ad hoc to update user accounting */ function update() external; /** * @notice method called ad hoc to clean up and perform additional accounting */ function clean() external; /** * @return gysr balance available for withdrawal */ function gysrBalance() external view returns (uint256); /** * @notice withdraw GYSR tokens applied during unstaking * @param amount number of GYSR to withdraw */ function withdraw(uint256 amount) external; } // 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; } // 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: GPL-3.0 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); } /* IRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEvents.sol"; import "../OwnerController.sol"; /** * @title Reward module interface * * @notice this contract defines the common interface that any reward module * must implement to be compatible with the modular Pool architecture. */ abstract contract IRewardModule is OwnerController, IEvents { // constants uint256 public constant DECIMALS = 18; /** * @return array of reward tokens */ function tokens() external view virtual returns (address[] memory); /** * @return array of reward token balances */ function balances() external view virtual returns (uint256[] memory); /** * @return GYSR usage ratio for reward module */ function usage() external view virtual returns (uint256); /** * @return address of module factory */ function factory() external view virtual returns (address); /** * @notice perform any necessary accounting for new stake * @param account address of staking account * @param user address of user * @param shares number of new shares minted * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function stake( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice reward user and perform any necessary accounting for unstake * @param account address of staking account * @param user address of user * @param shares number of shares burned * @param data additional data * @return amount of gysr spent * @return amount of gysr vested */ function unstake( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice reward user and perform and necessary accounting for existing stake * @param account address of staking account * @param user address of user * @param shares number of shares being claimed against * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function claim( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice method called by anyone to update accounting * @param user address of user for update * @dev will only be called ad hoc and should not contain essential logic */ function update(address user) external virtual; /** * @notice method called by owner to clean up and perform additional accounting * @dev will only be called ad hoc and should not contain any essential logic */ function clean() external virtual; } /* IEvents https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title GYSR event system * * @notice common interface to define GYSR event system */ interface IEvents { // staking event Staked( address indexed user, address indexed token, uint256 amount, uint256 shares ); event Unstaked( address indexed user, address indexed token, uint256 amount, uint256 shares ); event Claimed( address indexed user, address indexed token, uint256 amount, uint256 shares ); // rewards event RewardsDistributed( address indexed user, address indexed token, uint256 amount, uint256 shares ); event RewardsFunded( address indexed token, uint256 amount, uint256 shares, uint256 timestamp ); event RewardsUnlocked(address indexed token, uint256 shares); event RewardsExpired( address indexed token, uint256 amount, uint256 shares, uint256 timestamp ); // gysr event GysrSpent(address indexed user, uint256 amount); event GysrVested(address indexed user, uint256 amount); event GysrWithdrawn(uint256 amount); } /* ERC20BaseRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IRewardModule.sol"; /** * @title ERC20 base reward module * * @notice this abstract class implements common ERC20 funding and unlocking * logic, which is inherited by other reward modules. */ abstract contract ERC20BaseRewardModule is IRewardModule { using SafeERC20 for IERC20; // single funding/reward schedule struct Funding { uint256 amount; uint256 shares; uint256 locked; uint256 updated; uint256 start; uint256 duration; } // constants uint256 public constant INITIAL_SHARES_PER_TOKEN = 10**6; uint256 public constant MAX_ACTIVE_FUNDINGS = 16; // funding/reward state fields mapping(address => Funding[]) private _fundings; mapping(address => uint256) private _shares; mapping(address => uint256) private _locked; /** * @notice getter for total token shares */ function totalShares(address token) public view returns (uint256) { return _shares[token]; } /** * @notice getter for total locked token shares */ function lockedShares(address token) public view returns (uint256) { return _locked[token]; } /** * @notice getter for funding schedule struct */ function fundings(address token, uint256 index) public view returns ( uint256 amount, uint256 shares, uint256 locked, uint256 updated, uint256 start, uint256 duration ) { Funding storage f = _fundings[token][index]; return (f.amount, f.shares, f.locked, f.updated, f.start, f.duration); } /** * @param token contract address of reward token * @return number of active funding schedules */ function fundingCount(address token) public view returns (uint256) { return _fundings[token].length; } /** * @notice compute number of unlockable shares for a specific funding schedule * @param token contract address of reward token * @param idx index of the funding * @return the number of unlockable shares */ function unlockable(address token, uint256 idx) public view returns (uint256) { Funding storage funding = _fundings[token][idx]; // funding schedule is in future if (block.timestamp < funding.start) { return 0; } // empty if (funding.locked == 0) { return 0; } // handle zero-duration period or leftover dust from integer division if (block.timestamp >= funding.start + funding.duration) { return funding.locked; } return ((block.timestamp - funding.updated) * funding.shares) / funding.duration; } /** * @notice fund pool by locking up reward tokens for future distribution * @param token contract address of reward token * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked * @param start time (seconds) at which funding begins to unlock */ function _fund( address token, uint256 amount, uint256 duration, uint256 start ) internal { requireController(); // validate require(amount > 0, "rm1"); require(start >= block.timestamp, "rm2"); require(_fundings[token].length < MAX_ACTIVE_FUNDINGS, "rm3"); IERC20 rewardToken = IERC20(token); // do transfer of funding uint256 total = rewardToken.balanceOf(address(this)); rewardToken.safeTransferFrom(msg.sender, address(this), amount); uint256 actual = rewardToken.balanceOf(address(this)) - total; // mint shares at current rate uint256 minted = (total > 0) ? (_shares[token] * actual) / total : actual * INITIAL_SHARES_PER_TOKEN; _locked[token] += minted; _shares[token] += minted; // create new funding _fundings[token].push( Funding({ amount: amount, shares: minted, locked: minted, updated: start, start: start, duration: duration }) ); emit RewardsFunded(token, amount, minted, start); } /** * @dev internal function to clean up stale funding schedules * @param token contract address of reward token to clean up */ function _clean(address token) internal { // check for stale funding schedules to expire uint256 removed = 0; uint256 originalSize = _fundings[token].length; for (uint256 i = 0; i < originalSize; i++) { Funding storage funding = _fundings[token][i - removed]; uint256 idx = i - removed; if ( unlockable(token, idx) == 0 && block.timestamp >= funding.start + funding.duration ) { emit RewardsExpired( token, funding.amount, funding.shares, funding.start ); // remove at idx by copying last element here, then popping off last // (we don't care about order) _fundings[token][idx] = _fundings[token][ _fundings[token].length - 1 ]; _fundings[token].pop(); removed++; } } } /** * @dev unlocks reward tokens based on funding schedules * @param token contract addres of reward token * @return shares number of shares unlocked */ function _unlockTokens(address token) internal returns (uint256 shares) { // get unlockable shares for each funding schedule for (uint256 i = 0; i < _fundings[token].length; i++) { uint256 s = unlockable(token, i); Funding storage funding = _fundings[token][i]; if (s > 0) { funding.locked -= s; funding.updated = block.timestamp; shares += s; } } // do unlocking if (shares > 0) { _locked[token] -= shares; emit RewardsUnlocked(token, shares); } } /** * @dev distribute reward tokens to user * @param user address of user receiving rweard * @param token contract address of reward token * @param shares number of shares to be distributed * @return amount number of reward tokens distributed */ function _distribute( address user, address token, uint256 shares ) internal returns (uint256 amount) { // compute reward amount in tokens IERC20 rewardToken = IERC20(token); amount = (rewardToken.balanceOf(address(this)) * shares) / _shares[token]; // update overall reward shares _shares[token] -= shares; // do reward rewardToken.safeTransfer(user, amount); emit RewardsDistributed(user, token, amount, shares); } } /* GYSRUtils https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "./MathUtils.sol"; /** * @title GYSR utilities * * @notice this library implements utility methods for the GYSR multiplier * and spending mechanics */ library GysrUtils { using MathUtils for int128; // constants uint256 public constant DECIMALS = 18; uint256 public constant GYSR_PROPORTION = 10**(DECIMALS - 2); // 1% /** * @notice compute GYSR bonus as a function of usage ratio, stake amount, * and GYSR spent * @param gysr number of GYSR token applied to bonus * @param amount number of tokens or shares to unstake * @param total number of tokens or shares in overall pool * @param ratio usage ratio from 0 to 1 * @return multiplier value */ function gysrBonus( uint256 gysr, uint256 amount, uint256 total, uint256 ratio ) internal pure returns (uint256) { if (amount == 0) { return 0; } if (total == 0) { return 0; } if (gysr == 0) { return 10**DECIMALS; } // scale GYSR amount with respect to proportion uint256 portion = (GYSR_PROPORTION * total) / 10**DECIMALS; if (amount > portion) { gysr = (gysr * portion) / amount; } // 1 + gysr / (0.01 + ratio) uint256 x = 2**64 + (2**64 * gysr) / (10**(DECIMALS - 2) + ratio); return 10**DECIMALS + (uint256(int256(int128(uint128(x)).logbase10())) * 10**DECIMALS) / 2**64; } } /* OwnerController https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Owner controller * * @notice this base contract implements an owner-controller access model. * * @dev the contract is an adapted version of the OpenZeppelin Ownable contract. * It allows the owner to designate an additional account as the controller to * perform restricted operations. * * Other changes include supporting role verification with a require method * in addition to the modifier option, and removing some unneeded functionality. * * Original contract here: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ contract OwnerController { address private _owner; address private _controller; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event ControlTransferred( address indexed previousController, address indexed newController ); constructor() { _owner = msg.sender; _controller = msg.sender; emit OwnershipTransferred(address(0), _owner); emit ControlTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current controller. */ function controller() public view returns (address) { return _controller; } /** * @dev Modifier that throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "oc1"); _; } /** * @dev Modifier that throws if called by any account other than the controller. */ modifier onlyController() { require(_controller == msg.sender, "oc2"); _; } /** * @dev Throws if called by any account other than the owner. */ function requireOwner() internal view { require(_owner == msg.sender, "oc1"); } /** * @dev Throws if called by any account other than the controller. */ function requireController() internal view { require(_controller == msg.sender, "oc2"); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). This can * include renouncing ownership by transferring to the zero address. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual { requireOwner(); require(newOwner != address(0), "oc3"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers control of the contract to a new account (`newController`). * Can only be called by the owner. */ function transferControl(address newController) public virtual { requireOwner(); require(newController != address(0), "oc4"); emit ControlTransferred(_controller, newController); _controller = newController; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* MathUtils https://github.com/gysr-io/core SPDX-License-Identifier: BSD-4-Clause */ pragma solidity 0.8.4; /** * @title Math utilities * * @notice this library implements various logarithmic math utilies which support * other contracts and specifically the GYSR multiplier calculation * * @dev h/t https://github.com/abdk-consulting/abdk-libraries-solidity */ library MathUtils { /** * @notice calculate binary logarithm of x * * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function logbase2(int128 x) internal pure returns (int128) { unchecked { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(int256(x)) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } } /** * @notice calculate natural logarithm of x * @dev magic constant comes from ln(2) * 2^128 -> hex * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { unchecked { require(x > 0); return int128( int256( (uint256(int256(logbase2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128 ) ); } } /** * @notice calculate logarithm base 10 of x * @dev magic constant comes from log10(2) * 2^128 -> hex * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function logbase10(int128 x) internal pure returns (int128) { require(x > 0); return int128( int256( (uint256(int256(logbase2(x))) * 0x4d104d427de7fce20a6e420e02236748) >> 128 ) ); } // wrapper functions to allow testing function testlogbase2(int128 x) public pure returns (int128) { return logbase2(x); } function testlogbase10(int128 x) public pure returns (int128) { return logbase10(x); } } /* IPoolFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Pool factory interface * * @notice this defines the Pool factory interface, primarily intended for * the Pool contract to interact with */ interface IPoolFactory { /** * @return GYSR treasury address */ function treasury() external view returns (address); /** * @return GYSR spending fee */ function fee() external view returns (uint256); } /* IModuleFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Module factory interface * * @notice this defines the common module factory interface used by the * main factory to create the staking and reward modules for a new Pool. */ interface IModuleFactory { // events event ModuleCreated(address indexed user, address module); /** * @notice create a new Pool module * @param data binary encoded construction parameters * @return address of newly created module */ function createModule(bytes calldata data) external returns (address); } /* IStakingModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEvents.sol"; import "../OwnerController.sol"; /** * @title Staking module interface * * @notice this contract defines the common interface that any staking module * must implement to be compatible with the modular Pool architecture. */ abstract contract IStakingModule is OwnerController, IEvents { // constants uint256 public constant DECIMALS = 18; /** * @return array of staking tokens */ function tokens() external view virtual returns (address[] memory); /** * @notice get balance of user * @param user address of user * @return balances of each staking token */ function balances(address user) external view virtual returns (uint256[] memory); /** * @return address of module factory */ function factory() external view virtual returns (address); /** * @notice get total staked amount * @return totals for each staking token */ function totals() external view virtual returns (uint256[] memory); /** * @notice stake an amount of tokens for user * @param user address of user * @param amount number of tokens to stake * @param data additional data * @return address of staking account * @return number of shares minted for stake */ function stake( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice unstake an amount of tokens for user * @param user address of user * @param amount number of tokens to unstake * @param data additional data * @return address of staking account * @return number of shares burned for unstake */ function unstake( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice quote the share value for an amount of tokens without unstaking * @param user address of user * @param amount number of tokens to claim with * @param data additional data * @return address of staking account * @return number of shares that the claim amount is worth */ function claim( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice method called by anyone to update accounting * @param user address of user for update * @dev will only be called ad hoc and should not contain essential logic */ function update(address user) external virtual; /** * @notice method called by owner to clean up and perform additional accounting * @dev will only be called ad hoc and should not contain any essential logic */ function clean() external virtual; } /* Pool https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IPool.sol"; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IStakingModule.sol"; import "./interfaces/IRewardModule.sol"; import "./interfaces/IEvents.sol"; import "./OwnerController.sol"; /** * @title Pool * * @notice this implements the GYSR core Pool contract. It supports generalized * incentive mechanisms through a modular architecture, where * staking and reward logic is contained in child contracts. */ contract Pool is IPool, IEvents, ReentrancyGuard, OwnerController { using SafeERC20 for IERC20; // constants uint256 public constant DECIMALS = 18; // modules IStakingModule private immutable _staking; IRewardModule private immutable _reward; // gysr fields IERC20 private immutable _gysr; IPoolFactory private immutable _factory; uint256 private _gysrVested; /** * @param staking_ the staking module address * @param reward_ the reward module address * @param gysr_ address for GYSR token * @param factory_ address for parent factory */ constructor( address staking_, address reward_, address gysr_, address factory_ ) { _staking = IStakingModule(staking_); _reward = IRewardModule(reward_); _gysr = IERC20(gysr_); _factory = IPoolFactory(factory_); } // -- IPool -------------------------------------------------------------- /** * @inheritdoc IPool */ function stakingTokens() external view override returns (address[] memory) { return _staking.tokens(); } /** * @inheritdoc IPool */ function rewardTokens() external view override returns (address[] memory) { return _reward.tokens(); } /** * @inheritdoc IPool */ function stakingBalances(address user) external view override returns (uint256[] memory) { return _staking.balances(user); } /** * @inheritdoc IPool */ function stakingTotals() external view override returns (uint256[] memory) { return _staking.totals(); } /** * @inheritdoc IPool */ function rewardBalances() external view override returns (uint256[] memory) { return _reward.balances(); } /** * @inheritdoc IPool */ function usage() external view override returns (uint256) { return _reward.usage(); } /** * @inheritdoc IPool */ function stakingModule() external view override returns (address) { return address(_staking); } /** * @inheritdoc IPool */ function rewardModule() external view override returns (address) { return address(_reward); } /** * @inheritdoc IPool */ function stake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.stake(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.stake(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function unstake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.unstake(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.unstake(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function claim( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.claim(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.claim(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function update() external override nonReentrant { _staking.update(msg.sender); _reward.update(msg.sender); } /** * @inheritdoc IPool */ function clean() external override nonReentrant { requireController(); _staking.clean(); _reward.clean(); } /** * @inheritdoc IPool */ function gysrBalance() external view override returns (uint256) { return _gysrVested; } /** * @inheritdoc IPool */ function withdraw(uint256 amount) external override { requireController(); require(amount > 0, "p1"); require(amount <= _gysrVested, "p2"); // do transfer _gysr.safeTransfer(msg.sender, amount); _gysrVested = _gysrVested - amount; emit GysrWithdrawn(amount); } /** * @notice transfer control of the Pool and modules to another account * @param newController address of new controller */ function transferControl(address newController) public override { super.transferControl(newController); _staking.transferControl(newController); _reward.transferControl(newController); } // -- Pool internal ----------------------------------------------------- /** * @dev private method to process GYSR spending and vesting * @param spent number of tokens to unstake * @param vested data passed to staking module */ function _processGysr(uint256 spent, uint256 vested) private { // spending if (spent > 0) { _gysr.safeTransferFrom(msg.sender, address(this), spent); } // vesting if (vested > 0) { uint256 fee = (vested * _factory.fee()) / 10**DECIMALS; if (fee > 0) { _gysr.safeTransfer(_factory.treasury(), fee); } _gysrVested = _gysrVested + vested - fee; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } }
distributing fund to parties and staking contracts, and buying back PLBT from Sushiswap pool toStakersWETH amount of wETH to distribute to PLBTStakers toStakersWBTC amount of wBTC to distribute to PLBTStakers toLPStakers amount of PLBT to distribute to LPStakers on GYSR toOSOMWETH amount of wETH to distribute to PLBTStakers on OSOM toOSOMWBTC amount of wBTC to distribute to PLBTStakers on OSOM toBuyback amount of wETH to swap for PLBT
function distribute( uint256 toStakersWETH, uint256 toStakersWBTC, uint256 toLPStakers, uint256 toOSOMWETH, uint256 toOSOMWBTC, uint256 toBuyback ) external onlyRole(TREASURY_ROLE) { if (toStakersWETH != 0 && toStakersWBTC != 0) { weth.safeTransferFrom(treasury, address(staking), toStakersWETH); wbtc.safeTransferFrom(treasury, address(staking), toStakersWBTC); staking.setReward(toStakersWETH, toStakersWBTC); } if (toLPStakers != 0) { plbt.safeTransferFrom(treasury, address(this), toLPStakers); plbt.approve(gysr, toLPStakers); ERC20FriendlyRewardModule(gysr).fund(toLPStakers, 2592000); } if (toOSOMWETH != 0 && toOSOMWBTC != 0) { weth.safeTransferFrom(treasury, OSOM, toOSOMWETH); wbtc.safeTransferFrom(treasury, OSOM, toOSOMWBTC); } if (toBuyback != 0) { uint256 total = plbt.balanceOf(address(this)); weth.safeTransferFrom(treasury, address(this), toBuyback); address[] memory path = new address[](2); path[0] = address(weth); path[1] = address(plbt); uint256[] memory amounts = router.getAmountsOut(toBuyback, path); weth.approve(address(router), amounts[0]); router.swapTokensForExactTokens( amounts[1], amounts[0], path, address(this), block.timestamp + 600 ); uint256 current = plbt.balanceOf(address(this)); uint256 burn = current - total; plbt.safeTransfer(address(0), burn); } }
558,324
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @dev ERC20 Contract Implementation */ contract ERC20 { mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; string public constant name = 'Doom Cult Society DAO'; string public constant symbol = 'CUL'; uint256 public constant decimals = 18; uint256 public constant CURRENCY_MULTIPLIER = 1000000000000000000; uint256 internal constant ERROR_SIG = 0x08c379a000000000000000000000000000000000000000000000000000000000; bytes32 internal constant TRANSFER_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; bytes32 internal constant APPROVAL_SIG = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() {} function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256 result) { assembly { mstore(0x00, owner) mstore(0x20, _allowances.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, spender) result := sload(keccak256(0x00, 0x40)) } } function approve(address spender, uint256 amount) public returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance; assembly { // currentAllowance = _allowances[sender][msg.sender] mstore(0x00, sender) mstore(0x20, _allowances.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, caller()) let currentAllowanceSlot := keccak256(0x00, 0x40) currentAllowance := sload(currentAllowanceSlot) if gt(amount, currentAllowance) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 23) mstore(0x44, 'ERC20: amount>allowance') revert(0x00, 0x64) } } unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { assembly { mstore(0x00, sender) mstore(0x20, _balances.slot) let balancesSlot := keccak256(0x00, 0x40) let senderBalance := sload(balancesSlot) if or(or(iszero(sender), iszero(recipient)), gt(amount, senderBalance)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 32) mstore(0x44, 'ERC20: amount>balance or from==0') revert(0x00, 0x64) } sstore(balancesSlot, sub(senderBalance, amount)) mstore(0x00, recipient) balancesSlot := keccak256(0x00, 0x40) // skip overflow check as we only have 30,000 tokens sstore(balancesSlot, add(sload(balancesSlot), amount)) mstore(0x00, amount) log3(0x00, 0x20, TRANSFER_SIG, sender, recipient) } } function _approve( address owner, address spender, uint256 amount ) internal { assembly { if or(iszero(owner), iszero(spender)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 29) mstore(0x44, 'ERC20: approve from 0 address') revert(0x00, 0x64) } // _allowances[owner][spender] = amount mstore(0x00, owner) mstore(0x20, _allowances.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, spender) sstore(keccak256(0x00, 0x40), amount) // emit Approval(owner, spender, amount) mstore(0x00, amount) log3(0x00, 0x20, APPROVAL_SIG, owner, spender) } } } /** * @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 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 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); } /** * @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); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension but not the Enumerable extension */ contract ERC721 is IERC165, IERC721, IERC721Metadata { // Token name string public constant override name = 'Doom Cult Society'; // Token symbol string public constant override symbol = 'DCS'; uint256 internal constant ERROR_SIG = 0x08c379a000000000000000000000000000000000000000000000000000000000; // event signatures uint256 private constant APPROVAL_FOR_ALL_SIG = 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31; bytes32 internal constant TRANSFER_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; bytes32 internal constant APPROVAL_SIG = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _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() {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256 res) { assembly { if iszero(owner) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 42) mstore(0x44, 'ERC721: balance query for the ze') mstore(0x64, 'ro address') revert(0x00, 0x84) } mstore(0x00, owner) mstore(0x20, _balances.slot) res := sload(keccak256(0x00, 0x40)) } } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) // no need to mask address if we ensure everything written into _owners is an address owner := sload(keccak256(0x00, 0x40)) if iszero(owner) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 41) mstore(0x44, 'ERC721: owner query for nonexist') mstore(0x64, 'ent token') revert(0x00, 0x84) } } return owner; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256) public view virtual override returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); bool approvedForAll = isApprovedForAll(owner, msg.sender); /** * Failure cases * 1. to == owner (if ya wanna approve yourself go stare in a mirror!) * 2. !(msg.sender == owner OR approvedForAll == 1) */ assembly { if or(eq(to, owner), iszero(or(eq(caller(), owner), approvedForAll))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 19) mstore(0x44, 'ERC721: bad approve') revert(0x00, 0x64) } mstore(0x00, tokenId) mstore(0x20, _tokenApprovals.slot) sstore(keccak256(0x00, 0x40), to) log3(0x00, 0x20, APPROVAL_SIG, owner, to) } } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address res) { assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) if iszero(sload(keccak256(0x00, 0x40))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 19) mstore(0x44, 'ERC721: bad approve') revert(0x00, 0x64) } mstore(0x00, tokenId) mstore(0x20, _tokenApprovals.slot) res := sload(keccak256(0x00, 0x40)) } } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { assembly { if eq(operator, caller()) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 25) mstore(0x44, 'ERC721: approve to caller') revert(0x00, 0x64) } // _operatorApprovals[_msgSender()][operator] = approved mstore(0x00, caller()) mstore(0x20, _operatorApprovals.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, operator) sstore(keccak256(0x00, 0x40), approved) log4(0, 0, APPROVAL_FOR_ALL_SIG, caller(), operator, approved) } } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool res) { assembly { mstore(0x00, owner) mstore(0x20, _operatorApprovals.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, operator) res := sload(keccak256(0x00, 0x40)) } } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _isApprovedOrOwner(msg.sender, tokenId); _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 { _isApprovedOrOwner(msg.sender, tokenId); _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); bool isContract; assembly { isContract := gt(extcodesize(to), 0) } if (isContract) { _checkOnERC721ReceivedContract(from, to, tokenId, _data); } } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual { address owner; bool approvedForAll = isApprovedForAll(owner, spender); assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) owner := sload(keccak256(0x00, 0x40)) mstore(0x20, _tokenApprovals.slot) let approved := sload(keccak256(0x00, 0x40)) /** * Success Conditions * 1. spender = owner * 2. spender = approved * 3. approvedForAll = true * Also owner must NOT be 0 */ if or(iszero(or(or(eq(spender, owner), eq(approved, spender)), approvedForAll)), iszero(owner)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 44) mstore(0x44, 'ERC721: operator query for nonex') mstore(0x64, 'istent token') revert(0x00, 0x84) } } } /** * @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 { // address owner = ownerOf(tokenId); assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) let owner := sload(keccak256(0x00, 0x40)) // Clear approvals from the previous owner mstore(0x00, tokenId) mstore(0x20, _tokenApprovals.slot) sstore(keccak256(0x00, 0x40), 0) log3(0x00, 0x20, APPROVAL_SIG, owner, 0) log3(0x00, 0x20, TRANSFER_SIG, from, to) // _owners[tokenId] = to mstore(0x20, _owners.slot) sstore(keccak256(0x00, 0x40), to) // _balances[from] -= 1 mstore(0x00, from) mstore(0x20, _balances.slot) let slot := keccak256(0x00, 0x40) let fromBalance := sload(slot) sstore(slot, sub(fromBalance, 0x01)) // _balances[to] += 1 mstore(0x00, to) slot := keccak256(0x00, 0x40) sstore(slot, add(sload(slot), 1)) /** * Failure cases... * 1. owner != from * 2. to == 0 * 3. owner == 0 * 4. balances[from] == 0 */ if or(or(iszero(owner), iszero(fromBalance)), or(iszero(to), sub(owner, from))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 20) mstore(0x44, 'ERC721: bad transfer') revert(0x00, 0x64) } } } /** * @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 */ function _checkOnERC721ReceivedContract( address from, address to, uint256 tokenId, bytes memory _data ) internal { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { require( retval == IERC721Receiver(to).onERC721Received.selector, 'ERC721: transfer to non ERC721Receiver implementer' ); } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /** * @dev DoomCultSocietyDAO * Decentralized Autonomous Doom! Doooooooooooooooooooooooom! * * The DAO controls cultist tokens: CUL * Cultist tokens are sacrificed in order to mint DoomCultSociety NFTs */ contract DoomCultSocietyDAO is ERC20 { uint256 internal constant WEEKS_UNTIL_OBLIVION = 52; uint256 internal constant SECONDS_PER_WEEK = 604800; uint256 public sleepTimer; // can wake up once block.timestamp > sleepTimer uint256 public doomCounter; // number of weeks until contract is destroyed uint256 public timestampUntilNextEpoch; // countdown timer can decrease once block.timestamp > timestampUntilNextEpoch // potential max cultists (incl. currency multiplier. This is 30,000 CUL) uint256 internal constant MAX_CULTISTS = 30000000000000000000000; // how many do we actually start with? (phase 2 starts after 4 weeks regardless) uint256 public numStartingCultists; // If currentEpochTotalSacrificed <= lastEpocTotalSacrificed when epoch ends...kaboom! uint256 public currentEpochTotalSacrificed; uint256 public lastEpochTotalSacrificed; // How many times this week has the DAO been placated uint256 public placationCount; // How much does the cost increase by each time we placate? uint256 private constant PLACATE_INTERVAL = 100000000000000000; // 0.1 eth in wei // What is the current cost to placate? uint256 public placateThreshold = PLACATE_INTERVAL; uint256 private constant IT_HAS_AWOKEN_SIG = 0x21807e0b842b099372e0a04f56a3c00df1f88de6af9d3e3ebb06d4d6fac76a8d; event ItHasAwoken(uint256 startNumCultists); uint256 private constant COUNTDOWN_SIG = 0x11d2d22584d0bb23681c07ce6959f34dfc15469ad3546712ab96e3a945c6f603; event Countdown(uint256 weeksRemaining); uint256 private constant OBLITERATE_SIG = 0x03d6576f6c77df8600e2667de4d5c1fbc7cb69b42d5eaa80345d8174d80af46b; event Obliterate(uint256 endNumCultists); bool public isAwake; DoomCultSociety public doomCultSociety; modifier onlyAwake() { assembly { if iszero(and(sload(isAwake.slot), 1)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 14) mstore(0x44, 'It Is Sleeping') revert(0x00, 0x64) } } _; } modifier onlyAsleep() { assembly { if and(sload(isAwake.slot), 1) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 12) mstore(0x44, 'It Has Woken') revert(0x00, 0x64) } } _; } constructor() ERC20() { doomCultSociety = new DoomCultSociety(); assembly { sstore(sleepTimer.slot, add(timestamp(), mul(4, SECONDS_PER_WEEK))) } // Mmmmmmmmmmm slightly corrupt cheeky premine aka 6.66% founder reward _balances[address(0x24065d97424687EB9c83c87729fc1b916266F637)] = 898 * CURRENCY_MULTIPLIER; // some extra for givaways _balances[address(0x1E11a16335E410EB5f4e7A781C6f069609E5946A)] = 100 * CURRENCY_MULTIPLIER; // om _balances[address(0x9436630F6475D04E1d396a255f1321e00171aBFE)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x001aBc8196c60C2De9f9a2EdBdf8Db00C1Fa35ef)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x53DF4Fc15BdAfd4c01ca289797A85D00cC791810)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x10715Db3d70bBB01f39B6A6CA817cbcf2F6e9B5f)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x4a4866086D4b74521624Dbaec9478C9973Ff2C8e)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0xB658bF75C8968e8C9a577D5c8814803A1dDD0939)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x99A94D55417aaCC993889d5C574B07F01Ad35920)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0xE71f18D8F2e874AD3284C1A432A38fD158e35D70)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x31102499a64BEc6dC5Cc22FFDCBDc0551b2687Ab)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x934a19c7f2cD41D330d00C02884504fb59a33F36)] = 100 * CURRENCY_MULTIPLIER; // *burp* _totalSupply = 1998 * CURRENCY_MULTIPLIER; emit Transfer(address(0), address(0x24065d97424687EB9c83c87729fc1b916266F637), 898 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x1E11a16335E410EB5f4e7A781C6f069609E5946A), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x9436630F6475D04E1d396a255f1321e00171aBFE), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x001aBc8196c60C2De9f9a2EdBdf8Db00C1Fa35ef), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x53DF4Fc15BdAfd4c01ca289797A85D00cC791810), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x10715Db3d70bBB01f39B6A6CA817cbcf2F6e9B5f), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x4a4866086D4b74521624Dbaec9478C9973Ff2C8e), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0xB658bF75C8968e8C9a577D5c8814803A1dDD0939), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x99A94D55417aaCC993889d5C574B07F01Ad35920), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0xE71f18D8F2e874AD3284C1A432A38fD158e35D70), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x31102499a64BEc6dC5Cc22FFDCBDc0551b2687Ab), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x934a19c7f2cD41D330d00C02884504fb59a33F36), 100 * CURRENCY_MULTIPLIER); } /** * @dev Acquire cultists! */ function attractCultists() public onlyAsleep { assembly { if lt(MAX_CULTISTS, add(1, sload(_totalSupply.slot))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 22) mstore(0x44, 'No remaining cultists!') revert(0x00, 0x64) } let numTokens := mul(3, CURRENCY_MULTIPLIER) mstore(0x00, caller()) mstore(0x20, _balances.slot) let balanceSlot := keccak256(0x00, 0x40) // _balances[msg.sender] += 3 sstore(balanceSlot, add(sload(balanceSlot), numTokens)) // _totalSupply += 3 sstore(_totalSupply.slot, add(sload(_totalSupply.slot), numTokens)) // emit Transfer(0, msg.sender, 3) mstore(0x00, numTokens) log3(0x00, 0x20, TRANSFER_SIG, 0, caller()) } } /** * @dev Awaken the wrath of the Doom Cult Society DAO! */ function wakeUp() public onlyAsleep { assembly { if iszero( or(gt(add(sload(_totalSupply.slot), 1), MAX_CULTISTS), gt(add(timestamp(), 1), sload(sleepTimer.slot))) ) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 17) mstore(0x44, 'Still Sleeping...') revert(0x00, 0x64) } sstore(isAwake.slot, or(sload(isAwake.slot), 1)) sstore(timestampUntilNextEpoch.slot, add(timestamp(), SECONDS_PER_WEEK)) sstore(doomCounter.slot, 1) let total := sload(_totalSupply.slot) sstore(numStartingCultists.slot, div(total, CURRENCY_MULTIPLIER)) // emit ItHasAwoken(_totalSupply) mstore(0x00, total) log1(0x00, 0x20, IT_HAS_AWOKEN_SIG) } } function obliterate() internal onlyAwake { assembly { if iszero(eq(sload(doomCounter.slot), add(WEEKS_UNTIL_OBLIVION, 1))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 22) mstore(0x44, 'Too Soon To Obliterate') revert(0x00, 0x64) } // emit Obliterate(_totalSupply) mstore(0x00, sload(_totalSupply.slot)) log1(0x00, 0x20, OBLITERATE_SIG) selfdestruct(0x00) // so long and thanks for all the fish! } } /** * @dev This function will only generate ONE NFT regardless of how many you sacrifice!!!!! * If you want lots of NFTs call `sacrifice()` multiple times * This function is for those who just want to run those numbers up for maximum chaos * @param num number of cultists to sacrifice! */ function sacrificeManyButOnlyMintOneNFT( uint256 num, string memory /*message*/ ) public onlyAwake { uint256 totalRemainingCultists; uint256 totalSacrificedCultists; uint256 requiredTokens; assembly { requiredTokens := mul(CURRENCY_MULTIPLIER, num) mstore(0x00, caller()) mstore(0x20, _balances.slot) let slot := keccak256(0x00, 0x40) let userBal := sload(slot) if or(lt(userBal, requiredTokens), iszero(num)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 21) mstore(0x44, 'Insufficient Cultists') revert(0x00, 0x64) } sstore(slot, sub(userBal, requiredTokens)) sstore(currentEpochTotalSacrificed.slot, add(sload(currentEpochTotalSacrificed.slot), num)) let remainingTokens := sub(sload(_totalSupply.slot), requiredTokens) totalRemainingCultists := div(remainingTokens, CURRENCY_MULTIPLIER) sstore(_totalSupply.slot, remainingTokens) totalSacrificedCultists := sub(sload(numStartingCultists.slot), totalRemainingCultists) } doomCultSociety.mint(doomCounter, totalRemainingCultists, totalSacrificedCultists, msg.sender); assembly { // emit Transfer(msg.sender, 0, num) mstore(0x00, requiredTokens) log3(0x00, 0x20, TRANSFER_SIG, caller(), 0) } } /** * @dev BLOOD FOR THE BLOOD GOD! * * @param message commemorate your sacrifice with a message to be recorded for all eternity */ function sacrifice(string memory message) public onlyAwake { sacrificeManyButOnlyMintOneNFT(1, message); } /** * @dev Stuff the DAO with gold to soothe its wrath! When money talks, there are few interruptions. * * HOW IT WORKS * Users can push the required sacrifices down by 1 with some RAW ULTRA SOUND MONEY * Placate starts at 0.1 Eth, cost increases by 0.1 Eth per placation. * Yes, this gets stupid expensive very quickly! * * What do we do with these funds? Well, we could fairly redistribute them * to the DAO's stakeholders...but who has time to bother with writing that code? Certainly not me! * Instead send it to charity lol. Cults are supposed to take money from their supporters, not give it back! */ function placate() public payable onlyAwake { require(msg.value >= placateThreshold, 'TOO POOR'); uint256 numPlacations = msg.value / placateThreshold; placationCount += numPlacations; placateThreshold += (numPlacations * PLACATE_INTERVAL); // GiveDirectly Eth address (bool sent, ) = payable(0x750EF1D7a0b4Ab1c97B7A623D7917CcEb5ea779C).call{value: msg.value}(''); require(sent, 'Failed to send Ether'); } /** * @dev KNEEL PEON! KNEEL BEFORE YOUR MASTER! */ function worship() public payable onlyAwake { assembly { if gt(sload(timestampUntilNextEpoch.slot), add(timestamp(), 1)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 8) mstore(0x44, 'Too Soon') revert(0x00, 0x64) } } uint256 score = currentEpochTotalSacrificed + placationCount; if (lastEpochTotalSacrificed >= score) { assembly { // emit Obliterate(_totalSupply) mstore(0x00, sload(_totalSupply.slot)) log1(0x00, 0x20, OBLITERATE_SIG) selfdestruct(0x00) // womp womp } } assembly { sstore(lastEpochTotalSacrificed.slot, sload(currentEpochTotalSacrificed.slot)) sstore(currentEpochTotalSacrificed.slot, 0) sstore(timestampUntilNextEpoch.slot, add(timestamp(), SECONDS_PER_WEEK)) sstore(doomCounter.slot, add(sload(doomCounter.slot), 1)) sstore(placationCount.slot, 0) } if (doomCounter == (WEEKS_UNTIL_OBLIVION + 1)) { obliterate(); } // emit Countdown(doomCounter) assembly { mstore(0x00, sload(doomCounter.slot)) log1(0x00, 0x20, COUNTDOWN_SIG) } } } /** * @dev DoomCultSociety * It's more than a cult, it's a society! * We have culture, economic theories and heaps of dead cultists */ contract DoomCultSociety is ERC721 { address public doomCultSocietyDAO; uint256 private constant SPLIT_PHRASE_ACROSS_LINES = 31; constructor() ERC721() { assembly { sstore(doomCultSocietyDAO.slot, caller()) } mint(0, 30000, 0, address(this)); } // Not enumerable but hey we have enough info for this method...so why not // (until the DAO blows up that is!) function totalSupply() public view returns (uint256) { DoomCultSocietyDAO dao = DoomCultSocietyDAO(doomCultSocietyDAO); return dao.numStartingCultists() - (dao.totalSupply() / 1000000000000000000); } function mint( uint256 countdown, uint256 remainingCultists, uint256 sacrificedCultists, address owner ) public { uint256 tokenId; assembly { if iszero(eq(caller(), sload(doomCultSocietyDAO.slot))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 10) mstore(0x44, 'Bad Caller') revert(0x00, 0x64) } tokenId := add(add(mul(remainingCultists, 100000000), mul(countdown, 1000000)), sacrificedCultists) mstore(0x00, owner) mstore(0x20, _balances.slot) let slot := keccak256(0x00, 0x40) // no need to check overflow, there are only 30,000 tokens! sstore(slot, add(sload(slot), 1)) mstore(0x00, tokenId) mstore(0x20, _owners.slot) sstore(keccak256(0x00, 0x40), owner) mstore(0x00, tokenId) log3(0x00, 0x20, TRANSFER_SIG, 0, owner) } } function getImgData(uint256 tokenId) internal pure returns (string memory res) { // we make some assumptions when this function is called... // 1: a max of 480 bytes of RAM have been used so far (i.e. `getImgData` is called at start of call context!) // 2: setting the free memory pointer to 20000 won't cause any problems! assembly { { let t0 := '<use transform="' let t1 := ' transform="' let t2 := 'rotate' let t3 := ' fill="#f57914"' let t4 := ' fill="#ed1c24"' let t5 := ' fill="#8c1b85"' let t6 := ' fill="#0994d3"' let t7 := ' fill="#9addf0"' let t8 := ' fill="#312b5d"' let t9 := ' fill="#fff" ' let t10 := 'xlink:href="#' let t11 := '<circle cx="' let t12 := '<path id="' let t13 := '"/><use ' let t14 := '"><use ' let t15 := '="http://www.w3.org/' mstore(512, '<svg viewBox="0 0 700 800" xmlns') mstore(544, t15) mstore(564, '2000/svg" xmlns:xlink') mstore(585, t15) mstore(605, '1999/xlink"><style>.soft{font:70') mstore(637, '0 20px sans-serif;fill:#ffffff88') mstore(669, '}.heavy{font:700 29px sans-serif') mstore(701, ';fill:#fff}.superheavy{font:700 ') mstore(733, '40px sans-serif;fill:#fff}@-webk') mstore(765, 'it-keyframes shine {from {-webki') mstore(797, 't-filter: hue-') mstore(811, t2) mstore(817, '(0deg);}to { -webkit-filter: hue') mstore(849, '-') mstore(850, t2) mstore(856, '(360deg); } }g { -webkit-animati') mstore(888, 'on: shine 5s ease-in-out infinit') mstore(920, 'e; }</style><path d="M0 0h700v08') mstore(952, '00H0z"/><g') mstore(962, t1) mstore(974, 'matrix(.1 0 0 -.1 -350 660)"><de') mstore(1006, 'fs><g id="g">') mstore(1019, t11) mstore(1031, '-20" cy="210" r="100') mstore(1051, t13) mstore(1059, t10) mstore(1072, 'd') mstore(1073, t13) mstore(1081, 'transform="') mstore(1092, t2) mstore(1098, '(45 30.71 267.28)" ') mstore(1117, t10) mstore(1130, 'd') mstore(1131, t13) mstore(1139, 'transform="') mstore(1150, t2) mstore(1156, '(90 -20 240)" ') mstore(1170, t10) mstore(1183, 'd"/></g><g id="f') mstore(1199, t14) mstore(1206, t10) mstore(1219, 'c') mstore(1220, t13) mstore(1228, 'transform="') mstore(1239, t2) mstore(1245, '(45 -19.645 218.14)" ') mstore(1266, t10) mstore(1279, 'c') mstore(1280, t13) mstore(1288, 'transform="') mstore(1299, t2) mstore(1305, '(90 -30 230)" ') mstore(1319, t10) mstore(1332, 'c') mstore(1333, t13) mstore(1341, 'transform="') mstore(1352, t2) mstore(1358, '(-48 -37.302 218.45)" ') mstore(1380, t10) mstore(1393, 'c"/></g><g id="1') mstore(1409, t14) mstore(1416, 'fill="#f57914" ') mstore(1431, t10) mstore(1444, 'l') mstore(1445, t13) mstore(1453, 'transform="matrix(.44463 1.2216 ') mstore(1485, '-1.0337 .37622 7471.6 -2470.6)" ') mstore(1517, 'x="-2000"') mstore(1526, t8) mstore(1541, ' ') mstore(1542, t10) mstore(1555, 'e"/></g><g id="2"') mstore(1572, t1) mstore(1584, 'translate(5150 4100)') mstore(1604, t14) mstore(1611, 'fill="#ed1c24" ') mstore(1626, t10) mstore(1639, 'g') mstore(1640, t13) mstore(1648, 'fill="#8c1b85" ') mstore(1663, t10) mstore(1676, 'f"/></g><g id="3') mstore(1692, t14) mstore(1699, 'transform="scale(.9 -.7)" x="960') mstore(1731, '" y="-4400"') mstore(1742, t6) mstore(1757, ' ') mstore(1758, t10) mstore(1771, 'a') mstore(1772, t13) mstore(1780, 'transform="scale(.7 -.7) ') mstore(1805, t2) mstore(1811, '(40 14283 5801)"') mstore(1827, t4) mstore(1842, ' ') mstore(1843, t10) mstore(1856, 'a"/></g><g id="4"') mstore(1873, t1) mstore(1885, t2) mstore(1891, '(125 3495.9 1947) scale(.6)') mstore(1918, t14) mstore(1925, 'fill="#f57914" ') mstore(1940, t10) mstore(1953, 'g') mstore(1954, t13) mstore(1962, 'fill="#8c1b85" ') mstore(1977, t10) mstore(1990, 'f"/></g><g id="5') mstore(2006, t14) mstore(2013, 'transform="matrix(-1.4095 .51303') mstore(2045, ' .0684 -1.4083 12071 6071.6)" x=') mstore(2077, '"-2100" y="1650"') mstore(2093, t9) mstore(2106, t10) mstore(2119, 'e"/>') mstore(2123, t11) mstore(2135, '6470" cy="1780" r="130"') mstore(2158, t6) mstore(2173, '/>') mstore(2175, t11) mstore(2187, '5770" cy="1350" r="70"') mstore(2209, t4) mstore(2224, '/>') mstore(2226, t11) mstore(2238, '5820" cy="1150" r="70"') mstore(2260, t4) mstore(2275, '/>') mstore(2277, t11) mstore(2289, '5720" cy="1550" r="70"') mstore(2311, t4) mstore(2326, '/>') mstore(2328, t11) mstore(2340, '6190" cy="1700" r="80"') mstore(2362, t4) mstore(2377, '/></g><g id="6">') mstore(2393, t11) mstore(2405, '6000" cy="1650" r="80"') mstore(2427, t6) mstore(2442, '/>') mstore(2444, t11) mstore(2456, '6370" cy="200" r="80"') mstore(2477, t3) mstore(2492, '/><path d="M6300 1710c-7-13-6-26') mstore(2524, '-4-41s9-26 17-37c6-11 22-17 41-2') mstore(2556, '4 17-4 44 9 79 41 35 33 63 131 8') mstore(2588, '5 299-92-124-153-194-183-207-4-2') mstore(2620, '-9-4-13-6-10-4-17-13-22-24m-470-') mstore(2652, '161c-26 2-50-6-72-26-19-17-33-39') mstore(2684, '-39-65-4-13 20-164 72-452 50-286') mstore(2716, ' 181-530 393-731-201 421-292 709') mstore(2748, '-277 860 15 150 20 247 13 284-6 ') mstore(2780, '37-17 68-28 90-15 24-37 39-61 41') mstore(2812, '"') mstore(2813, t4) mstore(2828, '/></g><g id="7') mstore(2842, t14) mstore(2849, 'transform="scale(.9 1.6)" x="960') mstore(2881, '" y="-840"') mstore(2891, t6) mstore(2906, ' ') mstore(2907, t10) mstore(2920, 'a') mstore(2921, t13) mstore(2929, 'transform="') mstore(2940, t2) mstore(2946, '(-50 6340 4600)"') mstore(2962, t9) mstore(2975, t10) mstore(2988, 'h') mstore(2989, t13) mstore(2997, 'transform="scale(.9 1.3) ') mstore(3022, t2) mstore(3028, '(30 6740 4300)" x="400" y="-530"') mstore(3060, t4) mstore(3075, ' ') mstore(3076, t10) mstore(3089, 'a"/></g><g id="8"') mstore(3106, t1) mstore(3118, 'translate(7100 5100)') mstore(3138, t14) mstore(3145, 'transform="') mstore(3156, t2) mstore(3162, '(-100 -158.56 64.887) scale(.6)"') mstore(3194, t4) mstore(3209, ' ') mstore(3210, t10) mstore(3223, 'd') mstore(3224, t13) mstore(3232, 'transform="') mstore(3243, t2) mstore(3249, '(125) scale(.6)" ') mstore(3266, t10) mstore(3279, 'j') mstore(3280, t13) mstore(3288, 'transform="scale(-.6 .6) ') mstore(3313, t2) mstore(3319, '(-55 -272.14 -141.67)" ') mstore(3342, t10) mstore(3355, 'j"/></g><g id="j') mstore(3371, t14) mstore(3378, 'fill="#0994d3" ') mstore(3393, t10) mstore(3406, 'g') mstore(3407, t13) mstore(3415, 'fill="#8c1b85" ') mstore(3430, t10) mstore(3443, 'f"/></g><g id="l">') mstore(3461, t11) mstore(3473, '5630" cy="4060" r="140"/>') mstore(3498, t11) mstore(3510, '5400" cy="3850" r="110"/>') mstore(3535, t11) mstore(3547, '5270" cy="3600" r="90"/>') mstore(3571, t11) mstore(3583, '5180" cy="3350" r="70"/>') mstore(3607, t11) mstore(3619, '5150" cy="3150" r="60"/></g><g i') mstore(3651, 'd="q">') mstore(3657, t11) mstore(3669, '6840" cy="3060" r="165" style="f') mstore(3701, 'ill:#ed1344"/>') mstore(3715, t11) mstore(3727, '6770" cy="3335" r="165" style="f') mstore(3759, 'ill:#ed1344"/>') mstore(3773, t11) mstore(3785, '6640" cy="3535" r="165" style="f') mstore(3817, 'ill:#ed1344"/>') mstore(3831, t11) mstore(3843, '6395" cy="3690" r="165" style="f') mstore(3875, 'ill:#ed1344"/>') mstore(3889, t11) mstore(3901, '6840" cy="3060" r="80" style="fi') mstore(3933, 'll:#0994d3"/>') mstore(3946, t11) mstore(3958, '6770" cy="3335" r="80" style="fi') mstore(3990, 'll:#0994d3"/>') mstore(4003, t11) mstore(4015, '6640" cy="3535" r="80" style="fi') mstore(4047, 'll:#0994d3"/>') mstore(4060, t11) mstore(4072, '6395" cy="3690" r="80" style="fi') mstore(4104, 'll:#0994d3"/></g><g id="p') mstore(4129, t14) mstore(4136, t10) mstore(4149, 'q') mstore(4150, t13) mstore(4158, t10) mstore(4171, 'q"') mstore(4173, t1) mstore(4185, t2) mstore(4191, '(180 6150 3060)') mstore(4206, t13) mstore(4214, t10) mstore(4227, 'q"') mstore(4229, t1) mstore(4241, t2) mstore(4247, '(270 6150 3060)') mstore(4262, t13) mstore(4270, t10) mstore(4283, 'q"') mstore(4285, t1) mstore(4297, t2) mstore(4303, '(90 6150 3060)"/></g>') mstore(4324, t12) mstore(4334, 'n" d="M7507 5582c-168 33-340 50-') mstore(4366, '517 52-177-2-349-20-517-52-345-6') mstore(4398, '8-659-244-941-530-284-286-469-55') mstore(4430, '6-556-814-20-57-35-116-50-175-33') mstore(4462, '-138-48-284-46-436 0-452 74-803 ') mstore(4494, '220-1056 98-168 133-334 102-495-') mstore(4526, '30-159 20-308 148-441 68-68 122-') mstore(4558, '127 166-177 41-46 74-85 96-116 4') mstore(4590, '4-255 120-526 229-807 109-282 30') mstore(4622, '1-443 576-489 39-6 76-11 111-18 ') mstore(4654, '308-37 613-37 921 0 35 7 72 11 1') mstore(4686, '13 17 273 46 465 207 574 489 109') mstore(4718, ' 281 185 552 229 807 46 63 133 1') mstore(4750, '59 262 292s179 282 148 441c-30 1') mstore(4782, '61 4 327 103 495 146 253 220 605') mstore(4814, ' 223 1056-2 218-35 421-98 611-89') mstore(4846, ' 258-275 528-556 814-283 286-598') mstore(4878, ' 463-941 530" fill="#fcca07"/>') mstore(4908, t12) mstore(4918, 'm" d="M7243 1429c-2 24-10 43-26 ') mstore(4950, '61-15 17-34 26-54 26h-67c-21 0-4') mstore(4982, '1-9-57-26-15-17-24-37-22-61v-260') mstore(5014, 'c-2-24 6-44 22-61 15-17 35-26 57') mstore(5046, '-26h68c20 0 39 9 54 26s24 37 26 ') mstore(5078, '61v260m-9-487c-2 22-9 41-24 57-1') mstore(5110, '5 17-33 26-52 26h-65c-20 0-37-9-') mstore(5142, '52-26-15-15-22-35-22-57V695c0-22') mstore(5174, ' 6-41 22-57 15-15 33-24 52-24h65') mstore(5206, 'c20 0 37 8 52 24 15 15 22 35 24 ') mstore(5238, '57v246m82 86c-15-20-22-39-22-63l') mstore(5270, '.01-260c0-24 6-41 22-57 15-13 30') mstore(5302, '-17 50-13l59 13c20 4 35 15 50 35') mstore(5334, ' 6 11 13 24 15.34 37 2 9 4 17 4 ') mstore(5366, '24v242c0 24-6 41-20 57-15 15-30 ') mstore(5398, '22-50 19m263 60h-59c-20 0-37-9-5') mstore(5430, '4-24-15-15-22-33-22-52V816c0-17 ') mstore(5462, '6-35 22-48 15-11 31-15 46-13h9l5') mstore(5494, '8 15c17 4 32 13 46 28 13 17 20 3') mstore(5526, '5 20 52v204c0 20-6 35-20 48-13 1') mstore(5558, '3-28 20-46 20m294 373c-11 11-24 ') mstore(5590, '17-39 17h-50c-17 0-33-6-48-20-13') mstore(5622, '-13-20-28-20-48v-201c0-15 6-28 2') mstore(5654, '0-39 11-9 24-13 39-13h9l50 13c15') mstore(5686, ' 2 28 11 39 26s17 31 17 46v177c0') mstore(5718, ' 15-6 31-17 41m-480-65c0 22-7 41') mstore(5750, '-20 57-15 18-30 26-48 26h-58c-20') mstore(5782, ' 0-37-9-52-26s-22-37-22-61v-260c') mstore(5814, '0-24 6-43 22-59 15-15 33-20 52-1') mstore(5846, '7l59 6c17 2 33 13 48 33 13 17 20') mstore(5878, ' 37 20 59v242m381-262c-17-2-33-9') mstore(5910, '-48-24-13-15-20-30-17-50V892c-2-') mstore(5942, '15 4-28 17-37s26-13 41-11c2 2 4 ') mstore(5974, '2 6 2l52 17c15 7 28 15 39 31 11 ') mstore(6006, '15 17 33 17 48v178c0 15-6 28-17 ') mstore(6038, '39s-24 15-39 13l-52-4M7584 1488c') mstore(6070, '-15-15-22-33-22-52v-229c0-20 6-3') mstore(6102, '5 22-48 13-11 28-15 44-13h11l57 ') mstore(6134, '15c17 4 33 13 48 28 13 17 20 35 ') mstore(6166, '20 52v203c0 19-6 35-20 48-15 13-') mstore(6198, '30 20-48 20h-57c-20 0-39-9-55-24') mstore(6230, '"/>') mstore(6233, t12) mstore(6243, 'd" d="M0 0c4-54-1-112-17-177-9-4') mstore(6275, '0-18-73-31-103 7-32 21-61 36-83 ') mstore(6307, '28-48 53-71 78-73 22 4 39 31 54 ') mstore(6339, '81 8 34 12 75 11 115-19 22-36 47') mstore(6371, '-51 74C43-107 14-51 0 0"/>') mstore(6397, t12) mstore(6407, 'c" d="M250-340c41-36 75-48 96-40') mstore(6439, ' 21 12 25 46 14 95-5 30-15 59-28') mstore(6471, ' 88-8 17-14 37-25 56-8 17-20 34-') mstore(6503, '30 54-44 68-91 124-140 163-20 16') mstore(6535, '-40 28-55 36-15 4-27 7-37 4l-2-2') mstore(6567, 'c-4 0-7-5-9-7-7-9-10-21-12-38 0-') mstore(6599, '14 1-30 6-52 12-58 40-124 83-194') mstore(6631, ' 5-7 12-13 17-20 10-19 23-40 39-') mstore(6663, '57 28-33 56-63 85-86"/>') mstore(6686, t12) mstore(6696, 'o" d="M5960 3720c-33 9-76 20-127') mstore(6728, ' 33-94 28-150 35-166 24-17-11-28') mstore(6760, '-65-33-159-4-59-9-109-11-148-33-') mstore(6792, '11-72-26-122-46-92-33-142-61-150') mstore(6824, '-81-7-17 17-68 68-148 33-50 59-9') mstore(6856, '2 78-124-20-28-44-65-72-111-55-8') mstore(6888, '1-78-131-72-150 4-20 50-46 140-7') mstore(6920, '8 55-22 100-41 138-57 2-26 4-59 ') mstore(6952, '7-96v-35c4-98 15-153 31-164 15-1') mstore(6984, '1 68-6 161 17 57 15 105 26 142 3') mstore(7016, '5 22-26 50-61 83-103 61-76 102-1') mstore(7048, '13 122-116 20 0 59 37 120 109 37') mstore(7080, ' 46 68 85 94 113 33-7 76-20 129-') mstore(7112, '35 94-24 148-33 166-22 15 11 26 ') mstore(7144, '65 33 159 0 15 0 28 2 39 2 41 4 ') mstore(7176, '79 6 107 33 13 74 28 124 48 92 3') mstore(7208, '5 140 61 146 79 6 20-17 68-68 14') mstore(7240, '8-33 50-57 92-76 124 18 30 41 68') mstore(7272, ' 72 111 52 81 76 131 72 150-6 20') mstore(7304, '-52 48-142 81-54 22-100 39-135 5') mstore(7336, '4-2 35-4 78-6 133-4 98-15 153-30') mstore(7368, ' 164-15 13-70 6-161-17-59-15-107') mstore(7400, '-26-144-35-22 26-50 61-83 103-61') mstore(7432, ' 76-100 116-120 116s-61-37-120-1') mstore(7464, '11c-37-46-70-83-96-111"/>') mstore(7489, t12) mstore(7499, 'e" d="M6500 4100c-25 8-53 6-79-3') mstore(7531, '-31-8-53-28-62-53-11-25-8-53 5-7') mstore(7563, '8 11-22 31-39 56-53 11-6 25-11 3') mstore(7595, '9-17 87-31 182-90 289-177-53 213') mstore(7627, '-120 336-205 367-14 6-31 11-45 1') mstore(7659, '4"/>') mstore(7663, t12) mstore(7673, 'h" d="M5769 4876c274 21 415 85 6') mstore(7705, '92-127-115 159-241 266-379 326-8') mstore(7737, '9 36-218 80-316 63-70-13-117-37-') mstore(7769, '136-65-25-33-34-68-26-103s29-62 ') mstore(7801, '66-80c28-16 62-22 100-14"/>') mstore(7828, t12) mstore(7838, 'a" d="M6740 4300c-17-22-25-48-28') mstore(7870, '-78v-50c-3-98 34-230 109-401 62 ') mstore(7902, '168 93 303 92 400v50c-3 31-14 56') mstore(7934, '-31 78-20 25-45 39-70 39-28 0-53') mstore(7966, '-14-73-39"/><g id="z') mstore(7986, t14) mstore(7993, 'transform="') mstore(8004, t2) mstore(8010, '(130 6130 3100)"') mstore(8026, t7) mstore(8041, ' ') mstore(8042, t10) mstore(8055, 'l"/>') mstore(8059, t11) mstore(8071, '6665" cy="4440" r="80"') mstore(8093, t6) mstore(8108, '/>') mstore(8110, t11) mstore(8122, '6370" cy="4510" r="80"') mstore(8144, t6) mstore(8159, '/>') mstore(8161, t11) mstore(8173, '6480" cy="4360" r="60"') mstore(8195, t6) mstore(8210, '/><use') mstore(8216, t6) mstore(8231, ' ') mstore(8232, t10) mstore(8245, 'a"/>') mstore(8249, t11) mstore(8261, '7000" cy="3900" r="50"') mstore(8283, t6) mstore(8298, '/>') mstore(8300, t0) mstore(8316, t2) mstore(8322, '(-20 6500 4100)" x="110" y="50"') mstore(8353, t4) mstore(8368, ' ') mstore(8369, t10) mstore(8382, 'e') mstore(8383, t13) mstore(8391, 'fill="#ed1c24" ') mstore(8406, t10) mstore(8419, 'h"/>') mstore(8423, t11) mstore(8435, '5350" cy="2550" r="80"') mstore(8457, t4) mstore(8472, '/>') mstore(8474, t11) mstore(8486, '5420" cy="2280" r="130"') mstore(8509, t4) mstore(8524, '/>') mstore(8526, t11) mstore(8538, '5950" cy="4500" r="50"') mstore(8560, t4) mstore(8575, '/><path d="M5844 4593c36 36 81 5') mstore(8607, '3 134 56s90-17 109-53c20-36 14-7') mstore(8639, '3-17-104s-39-62-25-90c11-25 42-3') mstore(8671, '4 92-20s79 53 81 118c3 68-20 118') mstore(8703, '-73 151-53 34-109 50-174 50s-120') mstore(8735, '-22-168-70-70-104-70-168 22-120 ') mstore(8767, '70-168 140-90 280-132c126-42 252') mstore(8799, '-115 379-221-126 208-235 322-325') mstore(8831, ' 348-93 25-171 48-241 67s-106 56') mstore(8863, '-106 106 17 93 53 129"') mstore(8885, t6) mstore(8900, '/>') mstore(8902, t11) mstore(8914, '6160" cy="3050" r="600"') mstore(8937, t8) mstore(8952, '/><path d="M7145 1722c59 0 109 2') mstore(8984, '6 151 76 41 50 61 113 61 185s-19') mstore(9016, ' 135-61 185c-41 50-120 144-236 2') mstore(9048, '79-22 26-41 46-59 59-17-13-37-33') mstore(9080, '-59-59-116-135-194-229-236-279-4') mstore(9112, '1-50-63-113-61-185-2-72 20-135 6') mstore(9144, '1-186 41-50 92-76 151-76 55 0 10') mstore(9176, '3 24 144 70"') mstore(9188, t8) mstore(9203, '/><use') mstore(9209, t9) mstore(9222, t10) mstore(9235, 'm') mstore(9236, t13) mstore(9244, t10) } res := 480 mstore(0x40, 30000) // Token information // tokenId % 1,000,000 = index of token (i.e. how many were minted before this token) // (tokenId / 1,000,000) % 100 = week in which sacrificed occured (from game start) // (tokenId / 100,000,000) = number of cultists remaining after sacrifice let countdown := mod(div(tokenId, 1000000), 100) // SHINY??? if lt(countdown, 52) { // NO SHINY FOR YOU mstore8(898, 0x30) } mstore(0x00, tokenId) mstore(0x20, 5148293888310004) // some salt for your token let seed := keccak256(0x00, 0x40) // Store num living cultists at 0x00, not enough vars mstore(0x00, div(tokenId, 100000000)) let table1 := mload(0x40) let table2 := add(0x500, table1) let phrase1Seed := seed let phrase2Seed := shr(16, seed) let phrase3Seed := shr(32, seed) let phrase4Seed := shr(48, seed) let descSeed := shr(64, seed) let eyeSeed := shr(128, seed) let rare1Seed := shr(144, seed) let hueSeed := shr(160, seed) let p := 9257 mstore8(p, 0x30) // "0" if mod(descSeed, 3) { mstore8(p, add(0x30, mod(descSeed, 3))) // "1" or "2" } p := add(p, 0x01) let temp := '"/><use xlink:href="#' mstore(p, temp) p := add(p, 21) mstore8(p, 0x30) // "0" if mod(shr(16, descSeed), 3) { mstore8(p, add(0x32, mod(shr(16, descSeed), 3))) // "3" or "4" } p := add(p, 0x01) mstore(p, temp) p := add(p, 21) mstore8(p, 0x30) // "0" if mod(shr(32, descSeed), 3) { mstore8(p, add(0x34, mod(shr(32, descSeed), 3))) // "5" or "6" } p := add(p, 0x01) mstore(p, temp) p := add(p, 21) mstore8(p, 0x30) // "0" if mod(shr(48, descSeed), 3) { mstore8(p, add(0x36, mod(shr(48, descSeed), 3))) // "7" or "8" } p := add(p, 1) mstore(p, '"/></g></defs><g>') p := add(p, 17) // ARE WE BOUNCY???!! { /** IF LIVINGCULTISTS > 20000 ROLL 1% IF LIVINGCULTISTS < 20000 ROLL 2% IF LIVINGCULTISTS < 10000 ROLL 4% IF LIVINGCULTISTS < 2500 ROLL 8% IF LIVINGCULTISTS < 1250 ROLL 16% IF LIVINGCULTISTS < 625 ROLL 33% IF LIVINGCULTISTS < 200 ROLL 100% */ let isBouncy := eq(mod(shr(176, seed), 100), 0) if lt(mload(0x00), 20000) { isBouncy := eq(mod(shr(176, seed), 50), 0) } if lt(mload(0x00), 10000) { isBouncy := eq(mod(shr(176, seed), 25), 0) } if lt(mload(0x00), 2500) { isBouncy := eq(mod(shr(176, seed), 12), 0) } if lt(mload(0x00), 1250) { isBouncy := eq(mod(shr(176, seed), 6), 0) } if lt(mload(0x00), 625) { isBouncy := eq(mod(shr(176, seed), 3), 0) } if lt(mload(0x00), 200) { isBouncy := 1 } if isBouncy { // YESSSS WE BOUNCY let anim1 := '<animateTransform id="anim1" att' let anim2 := 'ributeName="transform" attribute' let anim3 := 'Type="XML" type="rotate" from="' let anim5 := ' repeatCount="repeat" dur="1s" b' let anim6 := 'egin="0s;anim2.end"/>' mstore(p, anim1) mstore(add(p, 32), anim2) mstore(add(p, 64), anim3) mstore(add(p, 96), '-20 6000 5000" to="20 8000 5000"') mstore(add(p, 128), anim5) mstore(add(p, 160), anim6) mstore(add(p, 181), anim1) mstore8(add(p, 207), 0x32) mstore(add(p, 213), anim2) mstore(add(p, 245), anim3) mstore(add(p, 277), '20 8000 5000" to="-20 6000 5000"') mstore(add(p, 309), anim5) mstore(add(p, 341), 'egin="anim1.end"/>') p := add(p, 359) } mstore(p, '<g filter="invert(') p := add(p, 18) } { // 1% change of inverting colours // increases to 50% iff week counter is 10 or greater let isWeekTenYet := gt(countdown, 9) let invertProbInv := add(mul(isWeekTenYet, 2), mul(iszero(isWeekTenYet), 100)) let inverted := eq(mod(rare1Seed, invertProbInv), 0) mstore8(p, add(0x30, inverted)) // "0" or "1" mstore(add(p, 1), ') hue-rotate(') let hue := mul(30, mod(hueSeed, 12)) // 0 to 360 in steps of 12 mstore8(add(p, 0xe), add(0x30, mod(div(hue, 100), 10))) mstore8(add(p, 0xf), add(0x30, mod(div(hue, 10), 10))) mstore8(add(p, 0x10), add(0x30, mod(hue, 10))) } p := add(p, 17) let eye2 { let eye1 := add(0x6f, and(eyeSeed, 1)) // "o" or "p" { let hasMixedEyes := eq(mod(shr(1, eyeSeed), 10), 0) switch hasMixedEyes case 1 { switch eq(eye1, 0x6f) case 1 { eye2 := 0x70 } case 0 { eye2 := 0x6f } } case 0 { eye2 := eye1 } } mstore(p, 'deg)"><use xlink:href="#n') mstore(add(p, 25), temp) p := add(p, 46) mstore8(p, eye1) // "o" or "p" mstore(add(p, 1), '" style="fill:#') mstore(0x00, 'ed1c24') mstore(0x20, '9addf0') mstore(add(p, 16), mload(shl(5, and(shr(2, eyeSeed), 1)))) p := add(p, 22) } /** Eye1 Animation */ { /** * ARE THE EYES SPINNY OR NOT? * IF NOT YET WEEK 12 ROLL AT 0.5% * IF AT LEAST WEEK 12 ROLL AT 2% * IF AT LEAST WEEK 24 ROLL AT 5% * IF AT LEAST WEEK 36 ROLL AT 20% * IF AT LEAST WEEK 48 ROLL AT 33% * IF WEEK 52 100% CONGRATULATIONS YOU ARE VERY SPINNY */ let rotatingEyes := mul(lt(countdown, 13), eq(mod(shr(3, eyeSeed), 200), 0)) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 11), eq(0, mod(shr(3, eyeSeed), 50)))) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 23), eq(0, mod(shr(3, eyeSeed), 20)))) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 35), eq(0, mod(shr(3, eyeSeed), 5)))) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 47), eq(0, mod(shr(3, eyeSeed), 3)))) rotatingEyes := add(rotatingEyes, gt(countdown, 51)) rotatingEyes := mul(5, gt(rotatingEyes, 0)) // set to 5s duration if any of the above triggers are hit let anim1 := '"><animateTransform attributeNam' let anim2 := 'e="transform" attributeType="XML' let anim3 := '" type="rotate" from="360 6160 3' let anim4 := '050" to="0 6160 3050" repeatCoun' let anim5 := 't="indefinite" dur="' mstore(p, anim1) mstore(add(p, 32), anim2) mstore(add(p, 64), anim3) mstore(add(p, 96), anim4) mstore(add(p, 128), anim5) mstore8(add(p, 148), add(0x30, rotatingEyes)) mstore(add(p, 149), 's" /></use><use xlink:href="#') // 179 p := add(p, 157) mstore(add(p, 21), 'z"/><g transform="matrix(-1 0 0 ') mstore(add(p, 53), '1 14000 0)"><use xlink:href="#') p := add(p, 83) mstore8(p, eye2) // "1" or "2" mstore(add(p, 1), '" style="fill:#') mstore(add(p, 16), mload(shl(5, and(shr(11, eyeSeed), 1)))) p := add(p, 22) mstore(p, anim1) mstore(add(p, 32), anim2) mstore(add(p, 64), anim3) mstore(add(p, 96), anim4) mstore(add(p, 128), anim5) mstore8(add(p, 148), add(0x30, rotatingEyes)) mstore(add(p, 149), 's"/></use><use xlink:href="#') } p := add(p, 156) mstore(add(p, 21), 'z"/></g></g></g></g><text x="10"') mstore(add(p, 53), ' y="25" class="soft">') p := add(p, 74) mstore(p, 'Week ') p := add(p, 5) switch gt(countdown, 9) case 1 { mstore8(p, add(0x30, mod(div(countdown, 10), 10))) // 0 or 1 mstore8(add(p, 1), add(0x30, mod(countdown, 10))) // 0 or 1 p := add(p, 2) } case 0 { mstore8(p, add(0x30, mod(countdown, 10))) // 0 or 1 p := add(p, 1) } mstore(p, '</text><text x="690" y="25" clas') mstore(add(p, 32), 's="soft" text-anchor="end">') p := add(p, 59) { let livingCultists := div(tokenId, 100000000) // 100 million switch eq(livingCultists, 0) case 1 { mstore8(p, 0x30) p := add(p, 1) } default { let t := livingCultists let len := 0 for { } t { } { t := div(t, 10) len := add(len, 1) } for { let i := 0 } lt(i, len) { i := add(i, 1) } { mstore8(add(p, sub(sub(len, 1), i)), add(mod(livingCultists, 10), 0x30)) livingCultists := div(livingCultists, 10) } p := add(p, len) } // mstore(p, ' Cultist') // mstore(add(p, 8), mul(iszero(oneCultist), 's')) // p := add(p, iszero(oneCultist)) // mstore(add(p, 8), ' Remaining') // p := add(p, 18) } mstore(p, '</text><text x="350" y="70" clas') mstore(add(p, 32), 's="heavy" text-anchor="middle">') p := add(p, 63) mstore(table1, 0) mstore(add(table1, 32), 'Willingly ') mstore(add(table1, 64), 'Enthusiastically ') mstore(add(table1, 96), 'Cravenly ') mstore(add(table1, 128), 'Gratefully ') mstore(add(table1, 160), 'Vicariously ') mstore(add(table1, 192), 'Shockingly ') mstore(add(table1, 224), 'Gruesomly ') mstore(add(table1, 256), 'Confusingly ') mstore(add(table1, 288), 'Angrily ') mstore(add(table1, 320), 'Mysteriously ') mstore(add(table1, 352), 'Shamefully ') mstore(add(table1, 384), 'Allegedly ') mstore(table2, 0) mstore(add(table2, 32), 10) mstore(add(table2, 64), 17) mstore(add(table2, 96), 9) mstore(add(table2, 128), 11) mstore(add(table2, 160), 12) mstore(add(table2, 192), 11) mstore(add(table2, 224), 10) mstore(add(table2, 256), 12) mstore(add(table2, 288), 8) mstore(add(table2, 320), 13) mstore(add(table2, 352), 11) mstore(add(table2, 384), 10) let idx := mul(iszero(mod(phrase1Seed, 10)), add(0x20, shl(5, mod(shr(8, phrase1Seed), 12)))) mstore(p, mload(add(table1, idx))) p := add(p, mload(add(table2, idx))) mstore(add(table1, 32), 'Banished To The Void Using') mstore(add(table1, 64), 'Crushed Under The Weight Of') mstore(add(table1, 96), 'Devoured By') mstore(add(table1, 128), 'Erased From Existence By') mstore(add(table1, 160), 'Extinguished By') mstore(add(table1, 192), 'Squished Into Nothingness By') mstore(add(table1, 224), 'Obliterated By') mstore(add(table1, 256), 'Ripped Apart By') mstore(add(table1, 288), 'Sacrificed In The Service Of') mstore(add(table1, 320), 'Slaughtered Defending') mstore(add(table1, 352), 'Suffered 3rd Degree Burns From') mstore(add(table1, 384), 'Torn To Shreds By') mstore(add(table1, 416), 'Vanished At A Party Hosted By') mstore(add(table1, 448), 'Vivisected Via') mstore(add(table1, 480), 'Lost Everything To') mstore(add(table1, 512), "Just Couldn't Cope With") mstore(add(table1, 544), 'Tried To Mess With') mstore(add(table1, 576), 'Scared To Death By') mstore(add(table1, 608), '"Dissapeared" For Sharing') mstore(add(table1, 640), 'Caught Red-Handed With') mstore(add(table1, 672), 'Caught Stealing') mstore(add(table1, 704), 'Lost A Fatal Game Of') mstore(add(table2, 32), 26) mstore(add(table2, 64), 27) mstore(add(table2, 96), 11) mstore(add(table2, 128), 24) mstore(add(table2, 160), 15) mstore(add(table2, 192), 28) mstore(add(table2, 224), 14) mstore(add(table2, 256), 15) mstore(add(table2, 288), 28) mstore(add(table2, 320), 21) mstore(add(table2, 352), 30) mstore(add(table2, 384), 17) mstore(add(table2, 416), 29) mstore(add(table2, 448), 14) mstore(add(table2, 480), 18) mstore(add(table2, 512), 23) mstore(add(table2, 544), 18) mstore(add(table2, 576), 18) mstore(add(table2, 608), 25) mstore(add(table2, 640), 22) mstore(add(table2, 672), 15) mstore(add(table2, 704), 20) idx := add(0x20, shl(5, mod(phrase2Seed, 22))) mstore(p, mload(add(table1, idx))) p := add(p, mload(add(table2, idx))) let lengthByte := add(p, 25) mstore(p, '</text><text x="350" y="720" cla') mstore(add(p, 32), 'ss="superheavy" text-anchor="mid') mstore(add(p, 64), 'dle">') p := add(p, 69) mstore(add(table1, 32), 'Anarcho-Capitalist ') mstore(add(table1, 64), 'Artificial ') mstore(add(table1, 96), 'Another Round Of ') mstore(add(table1, 128), 'Extreme ') mstore(add(table1, 160), 'Ferocious ') mstore(add(table1, 192), 'French ') mstore(add(table1, 224), 'Funkadelic ') mstore(add(table1, 256), 'Grossly Incompetent ') mstore(add(table1, 288), 'Hysterical ') mstore(add(table1, 320), 'Award-Winning ') mstore(add(table1, 352), 'Morally Bankrupt ') mstore(add(table1, 384), 'Overcollateralized ') mstore(add(table1, 416), 'Politically Indiscreet ') mstore(add(table1, 448), 'Punch-Drunk ') mstore(add(table1, 480), 'Punk ') mstore(add(table1, 512), 'Time-Travelling ') mstore(add(table1, 544), 'Unsophisticated ') mstore(add(table1, 576), 'Volcanic ') mstore(add(table1, 608), 'Voracious ') mstore(add(table1, 640), "Grandmother's Leftover ") mstore(add(table1, 672), "M. Night Shyamalan's ") mstore(add(table1, 704), 'Emergency British ') mstore(add(table1, 736), 'Oecumenical ') mstore(add(table1, 768), 'Another Round Of ') mstore(add(table1, 800), 'Self-Obsessed ') mstore(add(table1, 832), 'Number-Theoretic ') mstore(add(table1, 864), 'Award-Winning ') mstore(add(table1, 896), 'Chemically Enriched ') mstore(add(table1, 928), 'Winnie-The-Pooh Themed ') mstore(add(table1, 960), 'Gratuitously Violent ') mstore(add(table1, 992), 'Extremely Aggressive ') mstore(add(table1, 1024), 'Enraged ') mstore(add(table2, 32), 19) mstore(add(table2, 64), 11) mstore(add(table2, 96), 17) mstore(add(table2, 128), 8) mstore(add(table2, 160), 10) mstore(add(table2, 192), 7) mstore(add(table2, 224), 11) mstore(add(table2, 256), 20) mstore(add(table2, 288), 11) mstore(add(table2, 320), 14) mstore(add(table2, 352), 17) mstore(add(table2, 384), 19) mstore(add(table2, 416), 23) mstore(add(table2, 448), 12) mstore(add(table2, 480), 5) mstore(add(table2, 512), 16) mstore(add(table2, 544), 16) mstore(add(table2, 576), 9) mstore(add(table2, 608), 10) mstore(add(table2, 640), 23) mstore(add(table2, 672), 21) mstore(add(table2, 704), 18) mstore(add(table2, 736), 12) mstore(add(table2, 768), 17) mstore(add(table2, 800), 14) mstore(add(table2, 832), 17) mstore(add(table2, 864), 14) mstore(add(table2, 896), 20) mstore(add(table2, 928), 23) mstore(add(table2, 960), 21) mstore(add(table2, 992), 21) mstore(add(table2, 1024), 8) let rare := eq(mod(rare1Seed, 100), 0) // mmmm rare communism... idx := mul(iszero(rare), add(0x20, shl(5, mod(phrase3Seed, 32)))) let phrase3 := mload(add(table1, idx)) let phrase3Len := mload(add(table2, idx)) mstore(table1, 'The Communist Manifesto') mstore(add(table1, 32), 'Ballroom Dancing Fever') mstore(add(table1, 64), 'Canadians') mstore(add(table1, 96), 'Electric Jazz') mstore(add(table1, 128), 'Explosions') mstore(add(table1, 160), 'Insurance Fraud') mstore(add(table1, 192), 'Giant Gummy Bears') mstore(add(table1, 224), 'Gigawatt Lasers') mstore(add(table1, 256), 'Heavy Metal') mstore(add(table1, 288), 'Lifestyle Vloggers') mstore(add(table1, 320), 'Memes') mstore(add(table1, 352), 'Mathematicians') mstore(add(table1, 384), 'Rum Runners') mstore(add(table1, 416), 'Swine Flu') mstore(add(table1, 448), 'Theatre Critics') mstore(add(table1, 480), 'Trainee Lawyers') mstore(add(table1, 512), 'Twitterati') mstore(add(table1, 544), 'Velociraptors') mstore(add(table1, 576), 'Witches') mstore(add(table1, 608), 'Wizards') mstore(add(table1, 640), 'Z-List Celebrities') mstore(add(table1, 672), 'High-Stakes Knitting') mstore(add(table1, 704), 'Hardtack And Whiskey') mstore(add(table1, 736), 'Melodramatic Bullshit') mstore(add(table1, 768), '"Kidney Surprise"') mstore(add(table1, 800), 'Budget Cuts') mstore(add(table1, 832), 'Scurvy') mstore(add(table1, 864), 'Knife-Wielding Geese') mstore(add(table1, 896), 'Venture Capitalists') mstore(table2, 23) mstore(add(table2, 32), 22) mstore(add(table2, 64), 9) mstore(add(table2, 96), 13) mstore(add(table2, 128), 10) mstore(add(table2, 160), 15) mstore(add(table2, 192), 17) mstore(add(table2, 224), 15) mstore(add(table2, 256), 11) mstore(add(table2, 288), 18) mstore(add(table2, 320), 5) mstore(add(table2, 352), 14) mstore(add(table2, 384), 11) mstore(add(table2, 416), 9) mstore(add(table2, 448), 15) mstore(add(table2, 480), 15) mstore(add(table2, 512), 10) mstore(add(table2, 544), 13) mstore(add(table2, 576), 7) mstore(add(table2, 608), 7) mstore(add(table2, 640), 18) mstore(add(table2, 672), 20) mstore(add(table2, 704), 20) mstore(add(table2, 736), 21) mstore(add(table2, 768), 17) mstore(add(table2, 800), 11) mstore(add(table2, 832), 6) mstore(add(table2, 864), 20) mstore(add(table2, 896), 19) idx := mul(iszero(rare), add(0x20, shl(5, mod(phrase4Seed, 28)))) let phrase4 := mload(add(table1, idx)) let phrase4Len := mload(add(table2, idx)) switch gt(add(phrase3Len, phrase4Len), SPLIT_PHRASE_ACROSS_LINES) case 1 { mstore(p, '<tspan>') mstore(add(p, 7), phrase3) p := add(add(p, 7), phrase3Len) mstore(p, '</tspan><tspan x="350" dy="1.2em') mstore(add(p, 32), '">') mstore(add(p, 34), phrase4) p := add(p, add(34, phrase4Len)) mstore(p, '</tspan>') p := add(p, 8) } default { mstore(p, phrase3) mstore(add(p, phrase3Len), phrase4) p := add(p, add(phrase3Len, phrase4Len)) mstore8(lengthByte, 0x35) } // mstore(p, ) // p := add(p, ) mstore(p, '</text></svg>') p := add(p, 13) mstore(res, sub(sub(p, res), 0x20)) } } function tokenURI(uint256 tokenId) public pure override returns (string memory) { // 191 + length of tokenId uint256 strLen; uint256 tokenLen; uint256 id; assembly { id := mod(div(tokenId, 100000000), 1000000) let x := id for { } x { } { tokenLen := add(tokenLen, 1) x := div(x, 10) } tokenLen := add(tokenLen, iszero(id)) strLen := add(tokenLen, 191) } string memory innerData = Base64.encode(getImgData(tokenId), strLen, 2); assembly { let ptr := add(innerData, 0x20) mstore(ptr, '{"name": "Cultist #') ptr := add(ptr, 19) switch iszero(id) case 1 { mstore8(ptr, 0x30) ptr := add(ptr, 1) } case 0 { let i := tokenLen for { } id { } { i := sub(i, 1) mstore8(add(ptr, i), add(mod(id, 10), 0x30)) id := div(id, 10) } ptr := add(ptr, tokenLen) } mstore(ptr, '", "description": "Doom Cult Soc') mstore(add(ptr, 0x20), 'iety is an interactive cult simu') mstore(add(ptr, 0x40), 'lator. Acquire and sacrifice cul') mstore(add(ptr, 0x60), 'tists to hasten the end of the w') mstore(add(ptr, 0x80), 'orld.", "image": "data:image/svg') mstore( add(ptr, 0xa0), or('+xml;base64,', and(0xffffffffffffffffffffffffffffffffffffffff, mload(add(ptr, 0xa0)))) ) mstore(innerData, add(mload(innerData), strLen)) ptr := add(innerData, add(0x20, mload(innerData))) mstore(ptr, '"}') mstore(innerData, add(mload(innerData), 2)) } return string(abi.encodePacked('data:application/json;base64,', Base64.encode(innerData, 0, 0))); } function imageURI(uint256 tokenId) public pure returns (string memory) { string memory result = Base64.encode(getImgData(tokenId), 26, 0); assembly { let ptr := add(result, 0x20) mstore(ptr, or('data:image/svg+xml;base64,', and(0xffffffffffff, mload(ptr)))) mstore(result, add(mload(result), 26)) } return result; } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Original author Brecht Devos <brecht@loopring.org> /// @notice alterations have been made to this code library Base64 { /// @notice Encodes some bytes to the base64 representation // bytesBefore = prepend this many bytes to the output string // bytesAfter = append this many bytes to the output string function encode( string memory data, uint256 bytesBefore, uint256 bytesAfter ) internal pure returns (string memory result) { assembly { // ignore case where len = 0, shoudln't' happen with this contract let len := mload(data) // multiply by 4/3 rounded up let encodedLen := shl(2, div(add(len, 2), 3)) // Add some extra buffer at the end result := mload(0x40) mstore(0x40, add(add(result, encodedLen), add(0x20, add(bytesBefore, bytesAfter)))) let tablePtr := mload(0x40) mstore(add(tablePtr, 0x1f), 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef') mstore(add(tablePtr, 0x3f), 'ghijklmnopqrstuvwxyz0123456789+/') let resultPtr := add(result, add(32, bytesBefore)) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } } }
BLOOD FOR THE BLOOD GOD! message commemorate your sacrifice with a message to be recorded for all eternity/
function sacrifice(string memory message) public onlyAwake { sacrificeManyButOnlyMintOneNFT(1, message); }
629,332
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import 'base64-sol/base64.sol'; import './TheColors.sol'; import './INFTOwner.sol'; /** * @title TheSpirals contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract TheSpirals is ERC721Enumerable, Ownable { using Strings for uint256; using Strings for uint32; using Strings for uint8; struct SpiralTraits { uint8 direction; uint8 strokeWidth; uint8 spiralSize; uint8 stepDuration; uint8 duration; } string public PROVENANCE_HASH = ""; address constant public THE_COLORS = address(0x9fdb31F8CE3cB8400C7cCb2299492F2A498330a4); mapping(uint256 => bool) public hasClaimed; constructor() ERC721("The Spirals (thecolors.art)", "SPIRALS") {} function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { require(hasClaimed[tokenId], "ERC721Metadata: URI query for nonexistent token"); string memory svgData = generateSVGImage(tokenId); string memory image = Base64.encode(bytes(svgData)); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{', '"image":"', 'data:image/svg+xml;base64,', image, '",', generateNameDescription(tokenId), generateAttributes(tokenId), '}' ) ) ) ) ); } function getTokenMetadata(uint256 tokenId) public view returns (string memory) { string memory image = Base64.encode(bytes(generateSVGImage(tokenId))); return string( abi.encodePacked( 'data:application/json', '{', '"image":"', 'data:image/svg+xml;base64,', image, '",', generateNameDescription(tokenId), generateAttributes(tokenId), '}' ) ); } function getTokenSVG(uint256 tokenId) public view returns (string memory) { return generateSVGImage(tokenId); } function getBase64TokenSVG(uint256 tokenId) public view returns (string memory) { string memory image = Base64.encode(bytes(generateSVGImage(tokenId))); return string( abi.encodePacked( 'data:application/json;base64', image ) ); } function getColorsOwnedByUser(address user) public view returns (uint256[] memory tokenIds) { uint256[] memory tokenIds = new uint256[](4317); uint index = 0; for (uint i = 0; i < 4317; i++) { address tokenOwner = INFTOwner(THE_COLORS).ownerOf(i); if (user == tokenOwner) { tokenIds[index] = i; index += 1; } } uint left = 4317 - index; for (uint i = 0; i < left; i++) { tokenIds[index] = 9999; index += 1; } return tokenIds; } function getUnmintedSpiralsByUser(address user) public view returns (uint256[] memory tokenIds) { uint256[] memory tokenIds = new uint256[](4317); uint index = 0; for (uint i = 0; i < 4317; i++) { address tokenOwner = INFTOwner(THE_COLORS).ownerOf(i); if (user == tokenOwner && !hasClaimed[i]) { tokenIds[index] = i; index += 1; } } uint left = 4317 - index; for (uint i = 0; i < left; i++) { tokenIds[index] = 9999; index += 1; } return tokenIds; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { PROVENANCE_HASH = provenanceHash; } /** * Mints The Spirals */ function mintSpiral(uint256 tokenId) public { address tokenOwner = INFTOwner(THE_COLORS).ownerOf(tokenId); require(!hasClaimed[tokenId], "Color has already claimed their Spiral."); require(msg.sender == tokenOwner, "Only token owner can mint their Spiral."); uint32 r = TheColors(THE_COLORS).getRed(tokenId); uint32 g = TheColors(THE_COLORS).getGreen(tokenId); uint32 b = TheColors(THE_COLORS).getBlue(tokenId); _safeMint(msg.sender, tokenId); generateColorSpectrum(tokenId, r, g, b); hasClaimed[tokenId] = true; } function mintBatch(uint256[] memory tokenIds) public { for (uint256 i = 0; i < tokenIds.length; i++) { mintSpiral(tokenIds[i]); } } function generateNameDescription(uint256 tokenId) internal view returns (string memory) { string memory hexCode = TheColors(THE_COLORS).getHexColor(tokenId); return string( abi.encodePacked( '"external_url":"https://thecolors.art",', unicode'"description":"The Spirals are a set of 4,317 iconic designs generated and stored entirely on-chain, given to The Colors holders.', '\\nToken id: #', tokenId.toString(), '",', '"name":"The ', hexCode, ' Spiral",' ) ); } function generateAttributes(uint256 tokenId) internal view returns (string memory) { string memory hexCode = TheColors(THE_COLORS).getHexColor(tokenId); uint32 r = TheColors(THE_COLORS).getRed(tokenId); uint32 g = TheColors(THE_COLORS).getGreen(tokenId); uint32 b = TheColors(THE_COLORS).getBlue(tokenId); SpiralTraits memory traits = generateTraits(tokenId, r, g, b); bytes memory buffer = abi.encodePacked( '"attributes":[', '{"trait_type":"Background color","value":"', hexCode, '"},', '{"trait_type":"Type","value":"', getType(traits.direction), '"},', '{"trait_type":"Stroke","value":"', getStroke(traits.strokeWidth), '"},' ); return string( abi.encodePacked( buffer, '{"trait_type":"Size","value":"', getSize(traits.spiralSize), '"},', '{"trait_type":"Speed","value":"', getSpeed(traits.stepDuration), '"},', '{"trait_type":"Duration","value":"', traits.duration.toString(), 's"}', ']' ) ); } function getSpeed(uint8 stepDuration) internal view returns (string memory) { if (stepDuration == 1) { return "Fast"; } else if (stepDuration == 2) { return "Medium"; } else { return "Slow"; } } function getSize(uint8 spiralSize) internal view returns (string memory) { if (spiralSize == 5) { return "Small"; } else if (spiralSize == 6) { return "Kinda Small"; } else if (spiralSize == 7) { return "Small Medium"; } else if (spiralSize == 8) { return "Large Medium"; } else if (spiralSize == 9) { return "Kinda Large"; } else { return "Large"; } } function getType(uint8 direction) internal view returns (string memory) { if (direction == 2) { return "Flat"; } else if (direction == 3) { return "Semi-Flat"; } else if (direction == 4) { return "Semi-Straight"; } else { return "Straight"; } } function getStroke(uint8 strokeWidth) internal view returns (string memory) { if (strokeWidth < 3) { return "Thin"; } else if (strokeWidth < 5) { return "Semi-Thin"; } else if (strokeWidth < 7) { return "Semi-Thick"; } else { return "Thick"; } } function generateSVGImage(uint256 tokenId) internal view returns (string memory) { string memory hexCode = TheColors(THE_COLORS).getHexColor(tokenId); uint32 r = TheColors(THE_COLORS).getRed(tokenId); uint32 g = TheColors(THE_COLORS).getGreen(tokenId); uint32 b = TheColors(THE_COLORS).getBlue(tokenId); SpiralTraits memory traits = generateTraits(tokenId, r, g, b); string memory pathD = generatePathD(traits.direction, traits.spiralSize); bytes memory svgPartA = generateSVGPartA(tokenId, r, g, b, pathD, traits.strokeWidth, traits.stepDuration); bytes memory svgPartB = generateSVGPartB(pathD, traits.strokeWidth, traits.stepDuration, traits.duration); return string( abi.encodePacked( '<svg fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" style="background-color:', hexCode, '">', svgPartA, svgPartB, '</svg>' ) ); } function generateSVGPartB(string memory pathD, uint8 strokeWidth, uint8 stepDuration, uint8 duration) internal view returns (bytes memory) { bytes memory bufferA = abi.encodePacked( '<animate id="step5" begin="step4.end+0.5s" attributeType="XML" attributeName="stroke-dasharray" to="3217" dur="', stepDuration.toString(), 's" fill="freeze" />', '<animate id="step6" begin="step5.end+0.5s" attributeType="XML" attributeName="stroke-dasharray" to="6434" dur="', stepDuration.toString(), 's" fill="freeze" />', '</path>' '<path id="spiral" stroke-dasharray="0" stroke-dashoffset="0" stroke="#0000ff" stroke-width="' ); bytes memory bufferB = abi.encodePacked( strokeWidth.toString(), '" d="', pathD, '">' '<animate id="start" attributeType="XML" attributeName="stroke" begin="0.5s;end.end+0.5s" to="#0000ff" dur="', duration.toString(), '.5s" fill="freeze" />', '<animate attributeType="XML" attributeName="stroke-dashoffset" begin="start.begin" to="6434" dur="', duration.toString() ); bytes memory bufferC = abi.encodePacked( 's" fill="freeze" />', '<animate attributeType="XML" attributeName="stroke-dasharray" begin="start.begin" to="6434" dur="', duration.toString(), 's" fill="freeze" />', '<animate attributeType="XML" attributeName="stroke-dashoffset" begin="step6.end+1" to="0" dur="0.3s" fill="freeze" />', '<animate id="end" attributeType="XML" attributeName="stroke-dasharray" begin="step6.end+1" to="0" dur="0.3s" fill="freeze" />', '</path>' ); return abi.encodePacked(bufferA, bufferB, bufferC); } function generateSVGPartA(uint256 tokenId, uint32 r, uint32 g, uint32 b, string memory pathD, uint8 strokeWidth, uint8 stepDuration) internal view returns (bytes memory) { (string memory rHexCode, string memory gHexCode, string memory bHexCode) = generateColorSpectrum(tokenId, r, g, b); bytes memory bufferA = abi.encodePacked( '<path id="spiral" stroke-dasharray="6434" stroke-dashoffset="6434" stroke="', rHexCode, '" stroke-width="', strokeWidth.toString(), '" d="', pathD, '">', '<animate begin="start.begin" attributeType="XML" attributeName="stroke" to="', rHexCode, '" dur="0.3s" fill="freeze" />' ); bytes memory bufferB = abi.encodePacked( '<animate id="step1" begin="start.begin+0.5s" attributeType="XML" attributeName="stroke-dashoffset" to="0" dur="', stepDuration.toString(), 's" fill="freeze" />' '<animate id="step2" begin="step1.end+0.5s" attributeType="XML" attributeName="stroke-dasharray" to="0" dur="', stepDuration.toString(), 's" fill="freeze" />' '<animate begin="start.begin+6.5s" attributeType="XML" attributeName="stroke" to="', gHexCode, '" dur="0.3s" fill="freeze" />' ); bytes memory bufferC = abi.encodePacked( '<animate id="step3" begin="step2.end+1s" attributeType="XML" attributeName="stroke-dasharray" to="1608" dur="', stepDuration.toString(), 's" fill="freeze" />', '<animate id="step4" begin="step3.end+0.5s" attributeType="XML" attributeName="stroke-dashoffset" to="6434" dur="', stepDuration.toString(), 's" fill="freeze" />', '<animate begin="start.begin+13s" attributeType="XML" attributeName="stroke" to="', bHexCode, '" dur="0.3s" fill="freeze" />' ); return abi.encodePacked(bufferA, bufferB, bufferC); } function generatePathD(uint8 direction, uint8 spiralSize) internal view returns (string memory) { bytes memory pathD = abi.encodePacked("M250,250 a5,"); for (uint i = 0; i < 38; i++) { pathD = abi.encodePacked( pathD, direction.toString(), ' 0 1,1 ', i % 2 == 1 ? '-' : '', ((i + 2) * spiralSize).toString(), ',0 5,' ); } return string( abi.encodePacked( pathD, '0' ) ); } function generateTraits(uint256 tokenId, uint32 r, uint32 g, uint32 b) internal view returns (SpiralTraits memory) { SpiralTraits memory traits; traits.direction = uint8((_rng(tokenId, r + g + b) % 4) + 2); traits.strokeWidth = uint8((_rng(tokenId, r) % 8) + 1); traits.spiralSize = uint8((_rng(tokenId, g) % 6) + 5); traits.stepDuration = uint8((_rng(tokenId, b) % 3) + 1); traits.duration = uint8((_rng(tokenId, r + g) % 16) + 21); return traits; } function generateColorSpectrum(uint256 tokenId, uint32 r, uint32 g, uint32 b) internal view returns (string memory, string memory, string memory) { return ( string( abi.encodePacked( '#', uintToHexString(uint256(_rng(tokenId, r) % 16777215)) ) ), string( abi.encodePacked( '#', uintToHexString(uint256(_rng(tokenId, g) % 16777215)) ) ), string( abi.encodePacked( '#', uintToHexString(uint256(_rng(tokenId, b) % 16777215)) ) ) ); } function uintToHexString(uint256 number) public pure returns(string memory) { bytes32 value = bytes32(number); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(6); for (uint i = 0; i < 3; i++) { str[i*2] = alphabet[uint(uint8(value[i + 29] >> 4))]; str[1+i*2] = alphabet[uint(uint8(value[i + 29] & 0x0f))]; } return string(str); } function _rng(uint256 tokenId, uint256 seed) internal view returns(uint256) { uint256 _tokenId = tokenId + 1; return uint256(keccak256(abi.encodePacked(_tokenId.toString(), seed.toString()))) + uint256(_tokenId * seed); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "../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 /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import 'base64-sol/base64.sol'; import './INFTOwner.sol'; /** * @title TheColors contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract TheColors is ERC721Enumerable, Ownable { using Strings for uint256; using Strings for uint32; string public PROVENANCE_HASH = ""; address constant public THE_COLORS_LEGACY = address(0xc22f6c6f04c24Fac546A43Eb2E2eB10b1D2953DA); uint256 constant public MAX_COLORS = 4317; mapping(uint256 => uint32) private _hexColors; mapping(uint32 => bool) public existingHexColors; constructor() ERC721("The Colors (thecolors.art)", "COLORS") {} function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { require(_hexColors[tokenId] > 0, "ERC721Metadata: URI query for nonexistent token"); uint32 hexColor = _hexColors[tokenId]; string memory hexString = uintToHexString(hexColor); string memory image = Base64.encode(bytes(generateSVGImage(hexString))); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{', '"image":"', 'data:image/svg+xml;base64,', image, '",', '"image_data":"', escapeQuotes(generateSVGImage(hexString)), '",', generateNameDescription(tokenId, hexString), generateAttributes(hexColor, hexString), '}' ) ) ) ) ); } function getTokenMetadata(uint256 tokenId) public view returns (string memory) { uint32 hexColor = _hexColors[tokenId]; string memory hexString = uintToHexString(hexColor); string memory image = Base64.encode(bytes(generateSVGImage(hexString))); return string( abi.encodePacked( 'data:application/json', '{', '"image":"', 'data:image/svg+xml;base64,', image, '",', '"image_data":"', escapeQuotes(generateSVGImage(hexString)), '",', generateNameDescription(tokenId, hexString), generateAttributes(hexColor, hexString), '}' ) ); } function getTokenSVG(uint256 tokenId) public view returns (string memory) { uint32 hexColor = _hexColors[tokenId]; string memory hexString = uintToHexString(hexColor); return generateSVGImage(hexString); } function getBase64TokenSVG(uint256 tokenId) public view returns (string memory) { uint32 hexColor = _hexColors[tokenId]; string memory hexString = uintToHexString(hexColor); string memory image = Base64.encode(bytes(generateSVGImage(hexString))); return string( abi.encodePacked( 'data:application/json;base64', image ) ); } function getHexColor(uint256 tokenId) public view returns (string memory) { uint32 hexColor = _hexColors[tokenId]; string memory hexString = uintToHexString(hexColor); return string( abi.encodePacked( '#', hexString ) ); } function getRGB(uint256 tokenId) public view returns (string memory) { string memory r = getRed(tokenId).toString(); string memory g = getGreen(tokenId).toString(); string memory b = getBlue(tokenId).toString(); return string(abi.encodePacked('rgb(', r, ',', g, ',', b, ')')); } function getRed(uint256 tokenId) public view returns (uint32) { uint32 hexColor = _hexColors[tokenId]; return ((hexColor >> 16) & 0xFF); // Extract the RR byte } function getGreen(uint256 tokenId) public view returns (uint32) { uint32 hexColor = _hexColors[tokenId]; return ((hexColor >> 8) & 0xFF); // Extract the GG byte } function getBlue(uint256 tokenId) public view returns (uint32) { uint32 hexColor = _hexColors[tokenId]; return ((hexColor) & 0xFF); // Extract the BB byte } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { PROVENANCE_HASH = provenanceHash; } /** * Mints The Colors to The Colors Legacy holders */ function mintNextColors(uint256 numberOfTokens) public onlyOwner { require(totalSupply() + numberOfTokens <= MAX_COLORS, "Purchase would exceed max supply of Colors"); uint256 mintIndex; address tokenOwner; for(uint i = 0; i < numberOfTokens; i++) { mintIndex = totalSupply(); if (totalSupply() < MAX_COLORS) { tokenOwner = INFTOwner(THE_COLORS_LEGACY).ownerOf(mintIndex); _safeMint(tokenOwner, mintIndex); generateRandomHexColor(mintIndex); } } } function generateNameDescription(uint256 tokenId, string memory hexString) internal pure returns (string memory) { return string( abi.encodePacked( '"external_url":"https://thecolors.art",', unicode'"description":"The Colors are a set of 8,888 iconic shades generated and stored entirely on-chain to be used as a primitive and for color field vibes. ~ A Color is Forever ∞', '\\nHex: #', hexString, '\\n\\nToken id: #', tokenId.toString(), '",', '"name":"#', hexString, '",' ) ); } function generateAttributes(uint32 hexColor, string memory hexString) internal pure returns (string memory) { string memory r = ((hexColor >> 16) & 0xFF).toString(); // Extract the RR byte string memory g = ((hexColor >> 8) & 0xFF).toString(); // Extract the GG byte string memory b = ((hexColor) & 0xFF).toString(); // Extract the BB byte string memory rgb = string(abi.encodePacked('rgb(', r, ',', g, ',', b, ')')); return string( abi.encodePacked( '"attributes":[', '{"trait_type":"Hex code","value":"#', hexString, '"},' '{"trait_type":"RGB","value":"', rgb, '"},', '{"trait_type":"Red","value":"', r, '"},', '{"trait_type":"Green","value":"', g, '"},', '{"trait_type":"Blue","value":"', b, '"}', ']' ) ); } function generateSVGImage(string memory hexString) internal pure returns (string memory) { return string( abi.encodePacked( '<svg width="690" height="690" xmlns="http://www.w3.org/2000/svg" style="background-color:#', hexString, '">', '</svg>' ) ); } function generateRandomHexColor(uint256 tokenId) internal returns (uint32) { uint32 hexColor = uint32(_rng() % 16777215); while (existingHexColors[hexColor]) { hexColor = uint32(uint256(hexColor + block.timestamp * tokenId) % 16777215); } existingHexColors[hexColor] = true; _hexColors[tokenId] = hexColor; return hexColor; } function uintToHexString(uint256 number) public pure returns(string memory) { bytes32 value = bytes32(number); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(6); for (uint i = 0; i < 3; i++) { str[i*2] = alphabet[uint(uint8(value[i + 29] >> 4))]; str[1+i*2] = alphabet[uint(uint8(value[i + 29] & 0x0f))]; } return string(str); } function escapeQuotes(string memory symbol) internal pure returns (string memory) { bytes memory symbolBytes = bytes(symbol); uint quotesCount = 0; for (uint i = 0; i < symbolBytes.length; i++) { if (symbolBytes[i] == '"') { quotesCount++; } } if (quotesCount > 0) { bytes memory escapedBytes = new bytes(symbolBytes.length + (quotesCount)); uint256 index; for (uint i = 0; i < symbolBytes.length; i++) { if (symbolBytes[i] == '"') { escapedBytes[index++] = '\\'; } escapedBytes[index++] = symbolBytes[i]; } return string(escapedBytes); } return symbol; } function _rng() internal view returns(uint256) { return uint256(keccak256(abi.encodePacked(block.timestamp + block.difficulty))) + uint256(keccak256(abi.encodePacked(block.coinbase))) / block.number + block.gaslimit; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; interface INFTOwner { function ownerOf(uint256 tokenId) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; 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); }
Mints The Colors to The Colors Legacy holders/
function mintNextColors(uint256 numberOfTokens) public onlyOwner { require(totalSupply() + numberOfTokens <= MAX_COLORS, "Purchase would exceed max supply of Colors"); uint256 mintIndex; address tokenOwner; for(uint i = 0; i < numberOfTokens; i++) { mintIndex = totalSupply(); if (totalSupply() < MAX_COLORS) { tokenOwner = INFTOwner(THE_COLORS_LEGACY).ownerOf(mintIndex); _safeMint(tokenOwner, mintIndex); generateRandomHexColor(mintIndex); } } }
11,794,821
pragma solidity ^0.4.18; // 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 Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // 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/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // 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/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: 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/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/FlyCareToken.sol contract FlyCareToken is MintableToken, PausableToken, BurnableToken { string public constant name = "flyCARE Token"; string public constant symbol = "FCC"; uint8 public constant decimals = 18; function FlyCareToken() public { pause(); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: contracts/TokenCappedCrowdsale.sol /** * @title TokenCappedCrowdsale * @dev Extension of Crowdsale with a max amount of tokens sold */ contract TokenCappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public tokenSold; uint256 public tokenPresaleCap; uint256 public tokenPresaleSold; uint256 public saleStartTime; uint256 public totalTokenSaleCap; /** * @dev Constructor, takes presal cap, maximum number of tokens to be minted by the crowdsale and start date of regular sale period. * @param _tokenPresaleCap Max number of tokens to be sold during presale * @param _totalTokenSaleCap Max number of tokens to be minted * @param _saleStartTime Start date of the sale period */ function TokenCappedCrowdsale(uint256 _tokenPresaleCap, uint256 _totalTokenSaleCap, uint256 _saleStartTime) public { require(_tokenPresaleCap > 0); require(_totalTokenSaleCap > 0); tokenPresaleCap = _tokenPresaleCap; saleStartTime = _saleStartTime; totalTokenSaleCap = _totalTokenSaleCap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function tokenCapReached() public view returns (bool) { return tokenSold >= totalTokenSaleCap; } /** * @dev Extend parent behavior requiring purchase to respect the minting cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); // calculate token amount to be created uint256 tokenAmount = _getTokenAmount(_weiAmount); // Enforce presale cap before the begining of the sale if (block.timestamp < saleStartTime) { require(tokenPresaleSold.add(tokenAmount) <= tokenPresaleCap); } else { // Enfore total (presale + sale) token cap once the sale has started require(tokenSold.add(tokenAmount) <= totalTokenSaleCap); } } /** * @dev Extend parent behavior updating the number of token sold. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { super._processPurchase(_beneficiary, _tokenAmount); // update state // Keep track of all token sold in tokenSold tokenSold = tokenSold.add(_tokenAmount); // During presale only, keep track of token sold in tokenPresaleSold if (block.timestamp < saleStartTime) { tokenPresaleSold = tokenPresaleSold.add(_tokenAmount); } } } // File: zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: zeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: zeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts/FlyCareTokenSale.sol contract FlyCareTokenSale is RefundableCrowdsale, WhitelistedCrowdsale, TokenCappedCrowdsale, MintedCrowdsale, Pausable { using SafeMath for uint256; // Constants uint256 constant public RESERVE_AMOUNT = 70000000 * 10**18; // 50M FCC reserve + 20M FCC team and advisors // MAX_TEAM_AMOUNT = 20000000 // PreSale CAP : 32500000 // MainSale CAP : 97500000 uint256 constant public MIN_INVESTMENT = 0.1 * 10**18; // 0.1ETH minimal investment // Private uint64[5] private salePeriods; // Public address public whitelister; // Events event AddToWhitelist(address _beneficiary); function FlyCareTokenSale ( address _whitelister, uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _presaleCap, uint256 _totalTokenSaleCap, address _wallet, uint64[5] _salePeriods ) public Crowdsale(_rate, _wallet, new FlyCareToken()) TokenCappedCrowdsale(_presaleCap, _totalTokenSaleCap, _salePeriods[2]) TimedCrowdsale(_startTime, _endTime) RefundableCrowdsale(_goal) { require(_goal.mul(_rate) <= _totalTokenSaleCap); require(_whitelister != address(0)); for (uint8 i = 0; i < _salePeriods.length; i++) { require(_salePeriods[i] > 0); } salePeriods = _salePeriods; whitelister = _whitelister; } /** * @dev Extend parent behavior requiring the sale not to be paused. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(!paused); require(_weiAmount >= MIN_INVESTMENT); super._preValidatePurchase(_beneficiary, _weiAmount); } // descending rate function getCurrentRate() public view returns (uint256) { uint256 time = now; if (time <= salePeriods[0]) { return 4031; } if (time <= salePeriods[1]) { return 3794; } if (time <= salePeriods[2]) { return 3583; } if (time <= salePeriods[3]) { return 3395; } if (time <= salePeriods[4]) { return 3225; } return rate; } /** * @dev Overrides parent method taking into account variable rate. * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } /** * @dev Overrides TimedCrowdsale#hasClosed method to end sale permaturely if token cap has been reached. * @return Whether crowdsale has finished */ function hasClosed() public view returns (bool) { return tokenCapReached() || super.hasClosed(); } /******************************************* * Whitelisting related functions* *******************************************/ /** * @dev Change whitelister address to another one if provided by owner * @param _whitelister address of the new whitelister */ function setWhitelisterAddress(address _whitelister) external onlyOwner { require(_whitelister != address(0)); whitelister = _whitelister; } /** * @dev Modifier for address whith whitelisting rights */ modifier onlyWhitelister(){ require(msg.sender == whitelister); _; } /** * @dev Overrides addToWhitelist from WhitelistedCrowdsale to use a dedicated address instead of Owner * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyWhitelister { whitelist[_beneficiary] = true; AddToWhitelist(_beneficiary); } /** * @dev Overrides addToWhitelist from WhitelistedCrowdsale to use a dedicated address instead of Owner * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyWhitelister { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; AddToWhitelist(_beneficiaries[i]); } } /** * @dev Overrides addToWhitelist from WhitelistedCrowdsale to use a dedicated address instead of Owner * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyWhitelister { whitelist[_beneficiary] = false; } function finalization() internal { if (goalReached()) { if (!tokenCapReached()) { uint256 tokenUnsold = totalTokenSaleCap.sub(tokenSold); // Mint unsold tokens to sale's address & burn them immediately _deliverTokens(this, tokenUnsold); FlyCareToken(token).burn(tokenUnsold); } // Allocate remaining reserve to multisig wallet _deliverTokens(wallet, RESERVE_AMOUNT); // Finish token minting & unpause transfers require(FlyCareToken(token).finishMinting()); FlyCareToken(token).unpause(); } super.finalization(); } }
Mint unsold tokens to sale's address & burn them immediately
function finalization() internal { if (goalReached()) { if (!tokenCapReached()) { uint256 tokenUnsold = totalTokenSaleCap.sub(tokenSold); _deliverTokens(this, tokenUnsold); FlyCareToken(token).burn(tokenUnsold); } FlyCareToken(token).unpause(); } super.finalization(); }
13,400,144
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // ,|||||< ~|||||' `_+7ykKD%RDqmI*~` // [email protected]@@@@@8' `[email protected]@@@@` `^[email protected]@@@@@@@@@@@@@@@@R|` // [email protected]@@@@@@@Q; [email protected]@@@@J '}[email protected]@@@@@[email protected]@@@@@@Q, // [email protected]@@@@@@@@@j `[email protected]@@@Q` `[email protected]@@@@@h^` `[email protected]@@@@* // [email protected]@@@@@@@@@@@D. [email protected]@@@@i [email protected]@@@@w' ^@@@@@* // [email protected]@@@@[email protected]@@@@@@Q! `@@@@@Q ;@@@@@@; .txxxx: // |@@@@@u *@@@@@@@@z [email protected]@@@@* `[email protected]@@@@^ // `[email protected]@@@Q` '[email protected]@@@@@@R.'@@@@@B [email protected]@@@@% :DDDDDDDDDDDDDD5 // [email protected]@@@@7 `[email protected]@@@@@@[email protected]@@@@+ [email protected]@@@@K [email protected]@@@@@@* // `@@@@@Q` ^[email protected]@@@@@@@@@@W [email protected]@@@@@; ,[email protected]@@@@@# // [email protected]@@@@L ,[email protected]@@@@@@@@@! '[email protected]@@@@@u, [email protected]@@@@@@@^ // [email protected]@@@@Q }@@@@@@@@D '[email protected]@@@@@@@gUwwU%[email protected]@@@@@@@@@g // [email protected]@@@@< [email protected]@@@@@@; ;[email protected]@@@@@@@@@@@@@@Wf;[email protected]@@; // ~;;;;; .;;;;;~ '!Lx5mEEmyt|!' ;;;~ // // Powered By: @niftygateway // Author: @niftynathang // Collaborators: @conviction_1 // @stormihoebe // @smatthewenglish // @dccockfoster // @blainemalone import "./ERC721Omnibus.sol"; import "../interfaces/IERC2309.sol"; import "../interfaces/IERC721MetadataGenerator.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; import "../structs/NiftyType.sol"; import "../utils/Signable.sol"; import "../utils/Withdrawable.sol"; import "../utils/Royalties.sol"; contract NiftyERC721Token is ERC721Omnibus, Royalties, Signable, Withdrawable, IERC2309 { using Address for address; event NiftyTypeCreated(address indexed contractAddress, uint256 niftyType, uint256 idFirst, uint256 idLast); uint256 constant internal MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // A pointer to a contract that can generate token URI/metadata IERC721MetadataGenerator internal metadataGenerator; // Used to determine next nifty type/token ids to create on a mint call NiftyType internal lastNiftyType; // Sorted array of NiftyType definitions - ordered to allow binary searching NiftyType[] internal niftyTypes; // Mapping from Nifty type to IPFS hash of canonical artifact file. mapping(uint256 => string) private niftyTypeIPFSHashes; constructor() { } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Omnibus, Royalties, NiftyPermissions) returns (bool) { return interfaceId == type(IERC2309).interfaceId || super.supportsInterface(interfaceId); } function setMetadataGenerator(address metadataGenerator_) external { _requireOnlyValidSender(); if(metadataGenerator_ == address(0)) { metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } else { require(IERC165(metadataGenerator_).supportsInterface(type(IERC721MetadataGenerator).interfaceId), "Invalid Metadata Generator"); metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } } function finalizeContract() external { _requireOnlyValidSender(); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); collectionStatus.isContractFinalized = true; } function tokenURI(uint256 tokenId) public virtual view override returns (string memory) { if(address(metadataGenerator) == address(0)) { return super.tokenURI(tokenId); } else { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return metadataGenerator.tokenMetadata(tokenId, _getNiftyType(tokenId), bytes("")); } } function tokenIPFSHash(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return niftyTypeIPFSHashes[_getNiftyType(tokenId)]; } function setIPFSHash(uint256 niftyType, string memory ipfsHash) external { _requireOnlyValidSender(); require(bytes(niftyTypeIPFSHashes[niftyType]).length == 0, "ERC721Metadata: IPFS hash already set"); niftyTypeIPFSHashes[niftyType] = ipfsHash; } function mint(uint256[] calldata amounts, string[] calldata ipfsHashes) external { _requireOnlyValidSender(); require(amounts.length > 0 && ipfsHashes.length > 0, ERROR_INPUT_ARRAY_EMPTY); require(amounts.length == ipfsHashes.length, ERROR_INPUT_ARRAY_SIZE_MISMATCH); address to = collectionStatus.defaultOwner; require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); uint88 initialIdLast = lastNiftyType.idLast; uint72 nextNiftyType = lastNiftyType.niftyType; uint88 nextIdCounter = initialIdLast + 1; uint88 firstNewTokenId = nextIdCounter; uint88 lastIdCounter = 0; for(uint256 i = 0; i < amounts.length; i++) { require(amounts[i] > 0, ERROR_NO_TOKENS_MINTED); uint88 amount = uint88(amounts[i]); lastIdCounter = nextIdCounter + amount - 1; nextNiftyType++; if(bytes(ipfsHashes[i]).length > 0) { niftyTypeIPFSHashes[nextNiftyType] = ipfsHashes[i]; } niftyTypes.push(NiftyType({ isMinted: true, niftyType: nextNiftyType, idFirst: nextIdCounter, idLast: lastIdCounter })); emit NiftyTypeCreated(address(this), nextNiftyType, nextIdCounter, lastIdCounter); nextIdCounter += amount; } uint256 newlyMinted = lastIdCounter - initialIdLast; balances[to] += newlyMinted; lastNiftyType.niftyType = nextNiftyType; lastNiftyType.idLast = lastIdCounter; collectionStatus.amountCreated += uint88(newlyMinted); emit ConsecutiveTransfer(firstNewTokenId, lastIdCounter, address(0), to); } function setBaseURI(string calldata uri) external { _requireOnlyValidSender(); _setBaseURI(uri); } function exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } function burn(uint256 tokenId) public { _burn(tokenId); } function burnBatch(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, ERROR_INPUT_ARRAY_EMPTY); for(uint256 i = 0; i < tokenIds.length; i++) { _burn(tokenIds[i]); } } function getNiftyTypes() public view returns (NiftyType[] memory) { return niftyTypes; } function getNiftyTypeDetails(uint256 niftyType) public view returns (NiftyType memory) { uint256 niftyTypeIndex = MAX_INT; unchecked { niftyTypeIndex = niftyType - 1; } if(niftyTypeIndex >= niftyTypes.length) { revert('Nifty Type Does Not Exist'); } return niftyTypes[niftyTypeIndex]; } function _isValidTokenId(uint256 tokenId) internal virtual view override returns (bool) { return tokenId > 0 && tokenId <= collectionStatus.amountCreated; } // Performs a binary search of the nifty types array to find which nifty type a token id is associated with // This is more efficient than iterating the entire nifty type array until the proper entry is found. // This is O(log n) instead of O(n) function _getNiftyType(uint256 tokenId) internal virtual override view returns (uint256) { uint256 min = 0; uint256 max = niftyTypes.length - 1; uint256 guess = (max - min) / 2; while(guess < niftyTypes.length) { NiftyType storage guessResult = niftyTypes[guess]; if(tokenId >= guessResult.idFirst && tokenId <= guessResult.idLast) { return guessResult.niftyType; } else if(tokenId > guessResult.idLast) { min = guess + 1; guess = min + (max - min) / 2; } else if(tokenId < guessResult.idFirst) { max = guess - 1; guess = min + (max - min) / 2; } } return 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; abstract contract ERC721Omnibus is ERC721, IERC721DefaultOwnerCloneable { struct TokenOwner { bool transferred; address ownerAddress; } struct CollectionStatus { bool isContractFinalized; // 1 byte uint88 amountCreated; // 11 bytes address defaultOwner; // 20 bytes } // Only allow Nifty Entity to be initialized once bool internal initializedDefaultOwner; CollectionStatus internal collectionStatus; // Mapping from token ID to owner address mapping(uint256 => TokenOwner) internal ownersOptimized; function initializeDefaultOwner(address defaultOwner_) public { require(!initializedDefaultOwner, ERROR_REINITIALIZATION_NOT_PERMITTED); collectionStatus.defaultOwner = defaultOwner_; initializedDefaultOwner = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721DefaultOwnerCloneable).interfaceId || super.supportsInterface(interfaceId); } function getCollectionStatus() public view virtual returns (CollectionStatus memory) { return collectionStatus; } function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { require(_isValidTokenId(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); owner = ownersOptimized[tokenId].transferred ? ownersOptimized[tokenId].ownerAddress : collectionStatus.defaultOwner; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); } function _exists(uint256 tokenId) internal view virtual override returns (bool) { if(_isValidTokenId(tokenId)) { return ownersOptimized[tokenId].ownerAddress != address(0) || !ownersOptimized[tokenId].transferred; } return false; } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override returns (address owner, bool isApprovedOrOwner) { owner = ownerOf(tokenId); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } function _clearOwnership(uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = address(0); } function _setOwnership(address to, uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = to; } function _isValidTokenId(uint256 /*tokenId*/) internal virtual view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC2309 standard as defined in the EIP. */ interface IERC2309 { /** * @dev Emitted when consecutive token ids in range ('fromTokenId') to ('toTokenId') are transferred from one account (`fromAddress`) to * another (`toAddress`). * * Note that `value` may be zero. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721MetadataGenerator is IERC165 { function tokenMetadata(uint256 tokenId, uint256 niftyType, bytes calldata data) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721DefaultOwnerCloneable is IERC165 { function initializeDefaultOwner(address defaultOwner_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct NiftyType { bool isMinted; // 1 bytes uint72 niftyType; // 9 bytes uint88 idFirst; // 11 bytes uint88 idLast; // 11 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/ECDSA.sol"; import "../structs/SignatureStatus.sol"; abstract contract Signable is NiftyPermissions { event ContractSigned(address signer, bytes32 data, bytes signature); SignatureStatus public signatureStatus; bytes public signature; string internal constant ERROR_CONTRACT_ALREADY_SIGNED = "Contract already signed"; string internal constant ERROR_CONTRACT_NOT_SALTED = "Contract not salted"; string internal constant ERROR_INCORRECT_SECRET_SALT = "Incorrect secret salt"; string internal constant ERROR_SALTED_HASH_SET_TO_ZERO = "Salted hash set to zero"; string internal constant ERROR_SIGNER_SET_TO_ZERO = "Signer set to zero address"; function setSigner(address signer_, bytes32 saltedHash_) external { _requireOnlyValidSender(); require(signer_ != address(0), ERROR_SIGNER_SET_TO_ZERO); require(saltedHash_ != bytes32(0), ERROR_SALTED_HASH_SET_TO_ZERO); require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); signatureStatus.signer = signer_; signatureStatus.saltedHash = saltedHash_; signatureStatus.isSalted = true; } function sign(uint256 salt, bytes calldata signature_) external { require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); require(signatureStatus.isSalted, ERROR_CONTRACT_NOT_SALTED); address expectedSigner = signatureStatus.signer; bytes32 expectedSaltedHash = signatureStatus.saltedHash; require(_msgSender() == expectedSigner, ERROR_INVALID_MSG_SENDER); require(keccak256(abi.encodePacked(salt)) == expectedSaltedHash, ERROR_INCORRECT_SECRET_SALT); require(ECDSA.recover(ECDSA.toEthSignedMessageHash(expectedSaltedHash), signature_) == expectedSigner, ERROR_UNEXPECTED_DATA_SIGNER); signature = signature_; signatureStatus.isVerified = true; emit ContractSigned(expectedSigner, expectedSaltedHash, signature_); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./RejectEther.sol"; import "./NiftyPermissions.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; abstract contract Withdrawable is RejectEther, NiftyPermissions { /** * @dev Slither identifies an issue with sending ETH to an arbitrary destianation. * https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations * Recommended mitigation is to "Ensure that an arbitrary user cannot withdraw unauthorized funds." * This mitigation has been performed, as only the contract admin can call 'withdrawETH' and they should * verify the recipient should receive the ETH first. */ function withdrawETH(address payable recipient, uint256 amount) external { _requireOnlyValidSender(); require(amount > 0, ERROR_ZERO_ETH_TRANSFER); require(recipient != address(0), "Transfer to zero address"); uint256 currentBalance = address(this).balance; require(amount <= currentBalance, ERROR_INSUFFICIENT_BALANCE); //slither-disable-next-line arbitrary-send (bool success,) = recipient.call{value: amount}(""); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC20(address tokenContract, address recipient, uint256 amount) external { _requireOnlyValidSender(); bool success = IERC20(tokenContract).transfer(recipient, amount); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC721(address tokenContract, address recipient, uint256 tokenId) external { _requireOnlyValidSender(); IERC721(tokenContract).safeTransferFrom(address(this), recipient, tokenId, ""); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/Clones.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC2981.sol"; import "../interfaces/ICloneablePaymentSplitter.sol"; import "../structs/RoyaltyRecipient.sol"; abstract contract Royalties is NiftyPermissions, IERC2981 { event RoyaltyReceiverUpdated(uint256 indexed niftyType, address previousReceiver, address newReceiver); uint256 constant public BIPS_PERCENTAGE_TOTAL = 10000; // Royalty information mapped by nifty type mapping (uint256 => RoyaltyRecipient) internal royaltyRecipients; function supportsInterface(bytes4 interfaceId) public view virtual override(NiftyPermissions, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function getRoyaltySettings(uint256 niftyType) public view returns (RoyaltyRecipient memory) { return royaltyRecipients[niftyType]; } function setRoyaltyBips(uint256 niftyType, uint256 bips) external { _requireOnlyValidSender(); require(bips <= BIPS_PERCENTAGE_TOTAL, ERROR_BIPS_OVER_100_PERCENT); royaltyRecipients[niftyType].bips = uint16(bips); } function royaltyInfo(uint256 tokenId, uint256 salePrice) public virtual override view returns (address, uint256) { uint256 niftyType = _getNiftyType(tokenId); return royaltyRecipients[niftyType].recipient == address(0) ? (address(0), 0) : (royaltyRecipients[niftyType].recipient, (salePrice * royaltyRecipients[niftyType].bips) / BIPS_PERCENTAGE_TOTAL); } function initializeRoyalties(uint256 niftyType, address splitterImplementation, address[] calldata payees, uint256[] calldata shares) external returns (address) { _requireOnlyValidSender(); address previousReceiver = royaltyRecipients[niftyType].recipient; royaltyRecipients[niftyType].isPaymentSplitter = payees.length > 1; royaltyRecipients[niftyType].recipient = payees.length == 1 ? payees[0] : _clonePaymentSplitter(splitterImplementation, payees, shares); emit RoyaltyReceiverUpdated(niftyType, previousReceiver, royaltyRecipients[niftyType].recipient); return royaltyRecipients[niftyType].recipient; } function getNiftyType(uint256 tokenId) public view returns (uint256) { return _getNiftyType(tokenId); } function getPaymentSplitterByNiftyType(uint256 niftyType) public virtual view returns (address) { return _getPaymentSplitter(niftyType); } function getPaymentSplitterByTokenId(uint256 tokenId) public virtual view returns (address) { return _getPaymentSplitter(_getNiftyType(tokenId)); } function _getNiftyType(uint256 tokenId) internal virtual view returns (uint256) { return 0; } function _clonePaymentSplitter(address splitterImplementation, address[] calldata payees, uint256[] calldata shares_) internal returns (address) { require(IERC165(splitterImplementation).supportsInterface(type(ICloneablePaymentSplitter).interfaceId), ERROR_UNCLONEABLE_REFERENCE_CONTRACT); address clone = payable (Clones.clone(splitterImplementation)); ICloneablePaymentSplitter(clone).initialize(payees, shares_); return clone; } function _getPaymentSplitter(uint256 niftyType) internal virtual view returns (address) { return royaltyRecipients[niftyType].isPaymentSplitter ? royaltyRecipients[niftyType].recipient : address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721Errors.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC721Receiver.sol"; import "../interfaces/IERC721Metadata.sol"; import "../interfaces/IERC721Cloneable.sol"; import "../libraries/Address.sol"; import "../libraries/Context.sol"; import "../libraries/Strings.sol"; import "../utils/ERC165.sol"; import "../utils/GenericErrors.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}. */ abstract contract ERC721 is Context, ERC165, ERC721Errors, GenericErrors, IERC721Metadata, IERC721Cloneable { using Address for address; using Strings for uint256; // Only allow ERC721 to be initialized once bool internal initializedERC721; // Token name string internal tokenName; // Token symbol string internal tokenSymbol; // Base URI For Offchain Metadata string internal baseMetadataURI; // Mapping from token ID to owner address mapping(uint256 => address) internal owners; // Mapping owner address to token count mapping(address => uint256) internal balances; // Mapping from token ID to approved address mapping(uint256 => address) internal tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal operatorApprovals; function initializeERC721(string memory name_, string memory symbol_, string memory baseURI_) public override { require(!initializedERC721, ERROR_REINITIALIZATION_NOT_PERMITTED); tokenName = name_; tokenSymbol = symbol_; _setBaseURI(baseURI_); initializedERC721 = true; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Cloneable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), ERROR_QUERY_FOR_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), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return tokenName; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return tokenSymbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); string memory uriBase = baseURI(); return bytes(uriBase).length > 0 ? string(abi.encodePacked(uriBase, tokenId.toString())) : ""; } function baseURI() public view virtual returns (string memory) { return baseMetadataURI; } /** * @dev Internal function to set the base URI */ function _setBaseURI(string memory uri) internal { baseMetadataURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, ERROR_APPROVAL_TO_CURRENT_OWNER); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), ERROR_NOT_OWNER_NOR_APPROVED); _approve(owner, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), ERROR_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 { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); _transfer(owner, 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 { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), ERROR_NOT_AN_ERC721_RECEIVER); } /** * @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 (address owner, bool isApprovedOrOwner) { owner = owners[tokenId]; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } /** * @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 = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || tokenApprovals[tokenId] == _msgSender() || isApprovedForAll(owner, _msgSender())); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); // Clear approvals _clearApproval(owner, tokenId); balances[owner] -= 1; _clearOwnership(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 owner, address from, address to, uint256 tokenId) internal virtual { require(owner == from, ERROR_TRANSFER_FROM_INCORRECT_OWNER); require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); // Clear approvals from the previous owner _clearApproval(owner, tokenId); balances[from] -= 1; balances[to] += 1; _setOwnership(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Equivalent to approving address(0), but more gas efficient * * Emits a {Approval} event. */ function _clearApproval(address owner, uint256 tokenId) internal virtual { delete tokenApprovals[tokenId]; emit Approval(owner, address(0), tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address owner, address to, uint256 tokenId) internal virtual { tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _clearOwnership(uint256 tokenId) internal virtual { delete owners[tokenId]; } function _setOwnership(address to, uint256 tokenId) internal virtual { owners[tokenId] = to; } /** * @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 * * @dev Slither identifies an issue with unused return value. * Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return * This should be a non-issue. It is the standard OpenZeppelin implementation which has been heavily used and audited. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal 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(ERROR_NOT_AN_ERC721_RECEIVER); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract ERC721Errors { string internal constant ERROR_QUERY_FOR_ZERO_ADDRESS = "Query for zero address"; string internal constant ERROR_QUERY_FOR_NONEXISTENT_TOKEN = "Token does not exist"; string internal constant ERROR_APPROVAL_TO_CURRENT_OWNER = "Current owner approval"; string internal constant ERROR_APPROVE_TO_CALLER = "Approve to caller"; string internal constant ERROR_NOT_OWNER_NOR_APPROVED = "Not owner nor approved"; string internal constant ERROR_NOT_AN_ERC721_RECEIVER = "Not an ERC721Receiver"; string internal constant ERROR_TRANSFER_FROM_INCORRECT_OWNER = "Transfer from incorrect owner"; string internal constant ERROR_TRANSFER_TO_ZERO_ADDRESS = "Transfer to zero address"; string internal constant ERROR_ALREADY_MINTED = "Token already minted"; string internal constant ERROR_NO_TOKENS_MINTED = "No tokens minted"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./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.9; /** * @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.9; 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.9; import "./IERC721.sol"; interface IERC721Cloneable is IERC721 { function initializeERC721(string calldata name_, string calldata symbol_, string calldata baseURI_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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 pragma solidity 0.8.9; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; import "../interfaces/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.9; abstract contract GenericErrors { string internal constant ERROR_INPUT_ARRAY_EMPTY = "Input array empty"; string internal constant ERROR_INPUT_ARRAY_SIZE_MISMATCH = "Input array size mismatch"; string internal constant ERROR_INVALID_MSG_SENDER = "Invalid msg.sender"; string internal constant ERROR_UNEXPECTED_DATA_SIGNER = "Unexpected data signer"; string internal constant ERROR_INSUFFICIENT_BALANCE = "Insufficient balance"; string internal constant ERROR_WITHDRAW_UNSUCCESSFUL = "Withdraw unsuccessful"; string internal constant ERROR_CONTRACT_IS_FINALIZED = "Contract is finalized"; string internal constant ERROR_CANNOT_CHANGE_DEFAULT_OWNER = "Cannot change default owner"; string internal constant ERROR_UNCLONEABLE_REFERENCE_CONTRACT = "Uncloneable reference contract"; string internal constant ERROR_BIPS_OVER_100_PERCENT = "Bips over 100%"; string internal constant ERROR_NO_ROYALTY_RECEIVER = "No royalty receiver"; string internal constant ERROR_REINITIALIZATION_NOT_PERMITTED = "Re-initialization not permitted"; string internal constant ERROR_ZERO_ETH_TRANSFER = "Zero ETH Transfer"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; import "./ERC165.sol"; import "./GenericErrors.sol"; import "../interfaces/INiftyEntityCloneable.sol"; import "../interfaces/INiftyRegistry.sol"; import "../libraries/Context.sol"; abstract contract NiftyPermissions is Context, ERC165, GenericErrors, INiftyEntityCloneable { event AdminTransferred(address indexed previousAdmin, address indexed newAdmin); // Only allow Nifty Entity to be initialized once bool internal initializedNiftyEntity; // If address(0), use enable Nifty Gateway permissions - otherwise, specifies the address with permissions address public admin; // To prevent a mistake, transferring admin rights will be a two step process // First, the current admin nominates a new admin // Second, the nominee accepts admin address public nominatedAdmin; // Nifty Registry Contract INiftyRegistry internal permissionsRegistry; function initializeNiftyEntity(address niftyRegistryContract_) public { require(!initializedNiftyEntity, ERROR_REINITIALIZATION_NOT_PERMITTED); permissionsRegistry = INiftyRegistry(niftyRegistryContract_); initializedNiftyEntity = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(INiftyEntityCloneable).interfaceId || super.supportsInterface(interfaceId); } function renounceAdmin() external { _requireOnlyValidSender(); _transferAdmin(address(0)); } function nominateAdmin(address nominee) external { _requireOnlyValidSender(); nominatedAdmin = nominee; } function acceptAdmin() external { address nominee = nominatedAdmin; require(_msgSender() == nominee, ERROR_INVALID_MSG_SENDER); _transferAdmin(nominee); } function _requireOnlyValidSender() internal view { address currentAdmin = admin; if(currentAdmin == address(0)) { require(permissionsRegistry.isValidNiftySender(_msgSender()), ERROR_INVALID_MSG_SENDER); } else { require(_msgSender() == currentAdmin, ERROR_INVALID_MSG_SENDER); } } function _transferAdmin(address newAdmin) internal { address oldAdmin = admin; admin = newAdmin; delete nominatedAdmin; emit AdminTransferred(oldAdmin, newAdmin); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity 0.8.9; import "./Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct SignatureStatus { bool isSalted; bool isVerified; address signer; bytes32 saltedHash; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface INiftyEntityCloneable is IERC165 { function initializeNiftyEntity(address niftyRegistryContract_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface INiftyRegistry { function isValidNiftySender(address sendingKey) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @title A base contract that may be inherited in order to protect a contract from having its fallback function * invoked and to block the receipt of ETH by a contract. * @author Nathan Gang * @notice This contract bestows on inheritors the ability to block ETH transfers into the contract * @dev ETH may still be forced into the contract - it is impossible to block certain attacks, but this protects from accidental ETH deposits */ // For more info, see: "https://medium.com/@alexsherbuck/two-ways-to-force-ether-into-a-contract-1543c1311c56" abstract contract RejectEther { /** * @dev For most contracts, it is safest to explicitly restrict the use of the fallback function * This would generally be invoked if sending ETH to this contract with a 'data' value provided */ fallback() external payable { revert("Fallback function not permitted"); } /** * @dev This is the standard path where ETH would land if sending ETH to this contract without a 'data' value * In our case, we don't want our contract to receive ETH, so we restrict it here */ receive() external payable { revert("Receiving ETH not permitted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; import "../libraries/SafeERC20.sol"; interface ICloneablePaymentSplitter is IERC165 { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); function initialize(address[] calldata payees, uint256[] calldata shares_) external; function totalShares() external view returns (uint256); function totalReleased() external view returns (uint256); function totalReleased(IERC20 token) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address account) external view returns (uint256); function released(IERC20 token, address account) external view returns (uint256); function payee(uint256 index) external view returns (address); function release(address payable account) external; function release(IERC20 token, address account) external; function pendingPayment(address account) external view returns (uint256); function pendingPayment(IERC20 token, address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct RoyaltyRecipient { bool isPaymentSplitter; // 1 byte uint16 bips; // 2 bytes address recipient; // 20 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
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./ Clear approvals from the previous owner
function _transfer(address owner, address from, address to, uint256 tokenId) internal virtual { require(owner == from, ERROR_TRANSFER_FROM_INCORRECT_OWNER); require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); _clearApproval(owner, tokenId); balances[from] -= 1; balances[to] += 1; _setOwnership(to, tokenId); emit Transfer(from, to, tokenId); }
5,974,300
./partial_match/1/0xb0849647424573358B9ECc9EA4DAb4Bb32399def/sources/contracts/testContracts/EnumerableERC1155.sol
Returns if presale times are active for a given token/
function tokenPresaleTimeIsActive( uint256 _tokenId ) public view returns (bool) { if (tokenUsePresaleTimes[_tokenId] == false) { return true; } return block.timestamp >= tokenPresaleSaleStartTime[_tokenId] && block.timestamp <= tokenPresaleSaleEndTime[_tokenId]; }
2,690,672
/** *Submitted for verification at Etherscan.io on 2021-03-24 */ pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @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; } } /** * @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; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @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, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } interface IERC1155 { event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _amount, uint256 indexed _id); function mint( address _to, uint256 _id, uint256 _quantity, bytes calldata _data ) external; function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external returns (uint256 tokenId); function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data ) external; function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external; function balanceOf(address _owner, uint256 _id) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } /** * @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); } contract PoolTokenWrapper { using SafeMath for uint256; IERC20 public token; constructor(IERC20 _erc20Address) public { token = IERC20(_erc20Address); } uint256 private _totalSupply; // Objects balances [id][address] => balance mapping(uint256 => mapping(address => uint256)) internal _balances; mapping(uint256 => uint256) private _poolBalances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOfPool(uint256 id) public view returns (uint256) { return _poolBalances[id]; } function balanceOf(address account, uint256 id) public view returns (uint256) { return _balances[id][account]; } function stake(uint256 id, uint256 amount) public { _totalSupply = _totalSupply.add(amount); _poolBalances[id] = _poolBalances[id].add(amount); _balances[id][msg.sender] = _balances[id][msg.sender].add(amount); token.transferFrom(msg.sender, address(this), amount); } function withdraw(uint256 id, uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _poolBalances[id] = _poolBalances[id].sub(amount); _balances[id][msg.sender] = _balances[id][msg.sender].sub(amount); token.transfer(msg.sender, amount); } function transfer( uint256 fromId, uint256 toId, uint256 amount ) public { _poolBalances[fromId] = _poolBalances[fromId].sub(amount); _balances[fromId][msg.sender] = _balances[fromId][msg.sender].sub(amount); _poolBalances[toId] = _poolBalances[toId].add(amount); _balances[toId][msg.sender] = _balances[toId][msg.sender].add(amount); } function _rescuePineapples(address account, uint256 id) internal { uint256 amount = _balances[id][account]; _totalSupply = _totalSupply.sub(amount); _poolBalances[id] = _poolBalances[id].sub(amount); _balances[id][account] = _balances[id][account].sub(amount); token.transfer(account, amount); } } /** * FractionalExponents * Copied and modified from: * https://github.com/bancorprotocol/contracts/blob/master/solidity/contracts/converter/BancorFormula.sol#L289 * Redistributed Under Apache License 2.0: * https://github.com/bancorprotocol/contracts/blob/master/LICENSE * Provided as an answer to: * https://ethereum.stackexchange.com/questions/50527/is-there-any-efficient-way-to-compute-the-exponentiation-of-an-fractional-base-a */ contract FractionalExponents { uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; uint256[128] private maxExpArray; function BancorFormula() public { maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) { assert(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; assert(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; return res; } } contract DiggCollection is PoolTokenWrapper, Ownable, Pausable, FractionalExponents { using SafeMath for uint256; IERC1155 public memeLtd; uint256 constant multiplyer = 1000; uint256 constant min = 1e15; struct Card { uint256 points; uint256 releaseTime; uint256 mintFee; } struct Pool { uint256 periodStart; uint256 feesCollected; uint256 spentPineapples; uint256 controllerShare; address artist; mapping(address => uint256) lastUpdateTime; mapping(address => uint256) points; mapping(uint256 => Card) cards; } address public controller; address public rescuer; mapping(address => uint256) public pendingWithdrawals; mapping(uint256 => Pool) public pools; event UpdatedArtist(uint256 poolId, address artist); event PoolAdded(uint256 poolId, address artist, uint256 periodStart); event CardAdded(uint256 poolId, uint256 cardId, uint256 points, uint256 mintFee, uint256 releaseTime); event Staked(address indexed user, uint256 poolId, uint256 amount); event Withdrawn(address indexed user, uint256 poolId, uint256 amount); event Transferred(address indexed user, uint256 fromPoolId, uint256 toPoolId, uint256 amount); event Redeemed(address indexed user, uint256 poolId, uint256 amount); modifier updateReward(address account, uint256 id) { if (account != address(0)) { pools[id].points[account] = earned(account, id); pools[id].lastUpdateTime[account] = block.timestamp; } _; } modifier poolExists(uint256 id) { require(pools[id].periodStart > 0, "pool does not exists"); _; } modifier cardExists(uint256 pool, uint256 card) { require(pools[pool].cards[card].points > 0, "card does not exists"); _; } constructor( address _controller, IERC1155 _memeLtdAddress, IERC20 _tokenAddress ) public PoolTokenWrapper(_tokenAddress) { controller = _controller; memeLtd = _memeLtdAddress; } function cardMintFee(uint256 pool, uint256 card) public view returns (uint256) { return pools[pool].cards[card].mintFee; } function cardReleaseTime(uint256 pool, uint256 card) public view returns (uint256) { return pools[pool].cards[card].releaseTime; } function cardPoints(uint256 pool, uint256 card) public view returns (uint256) { return pools[pool].cards[card].points; } function timeElapsed(address account, uint256 pool) public view returns (uint256) { return block.timestamp.sub(pools[pool].lastUpdateTime[account]); } function earned(address account, uint256 pool) public view returns (uint256) { Pool storage p = pools[pool]; uint256 blockTime = block.timestamp; uint256 poolBalance = balanceOf(account, pool); if (poolBalance < min) return p.points[account]; // psuedomath: rewardRate = (1.35 * (balance * 1000)^(1/4)) / 86400 (uint256 mantissa, uint8 exponent) = power(multiplyer.mul(poolBalance), uint256(1e18), 1, 4); uint256 noCoefficient = mantissa.mul(uint256(1 ether)).div(uint256(1) << uint256(exponent)); uint256 rewardRate = noCoefficient.mul(135).div(8640000); return rewardRate.mul(blockTime.sub(p.lastUpdateTime[account])).add(p.points[account]); } // override PoolTokenWrapper's stake() function function stake(uint256 pool, uint256 amount) public poolExists(pool) updateReward(msg.sender, pool) whenNotPaused() { Pool memory p = pools[pool]; require(block.timestamp >= p.periodStart, "pool not open"); require(amount.add(balanceOf(msg.sender, pool)) >= min, "must stake min"); super.stake(pool, amount); emit Staked(msg.sender, pool, amount); } // override PoolTokenWrapper's withdraw() function function withdraw(uint256 pool, uint256 amount) public poolExists(pool) updateReward(msg.sender, pool) { require(amount > 0, "cannot withdraw 0"); super.withdraw(pool, amount); emit Withdrawn(msg.sender, pool, amount); } // override PoolTokenWrapper's transfer() function function transfer( uint256 fromPool, uint256 toPool, uint256 amount ) public poolExists(fromPool) poolExists(toPool) updateReward(msg.sender, fromPool) updateReward(msg.sender, toPool) whenNotPaused() { Pool memory toP = pools[toPool]; require(block.timestamp >= toP.periodStart, "pool not open"); super.transfer(fromPool, toPool, amount); emit Transferred(msg.sender, fromPool, toPool, amount); } function transferAll(uint256 fromPool, uint256 toPool) external { transfer(fromPool, toPool, balanceOf(msg.sender, fromPool)); } function exit(uint256 pool) external { withdraw(pool, balanceOf(msg.sender, pool)); } function redeem(uint256 pool, uint256 card) public payable poolExists(pool) cardExists(pool, card) updateReward(msg.sender, pool) { Pool storage p = pools[pool]; Card memory c = p.cards[card]; require(block.timestamp >= c.releaseTime, "card not released"); require(p.points[msg.sender] >= c.points, "not enough pineapples"); require(msg.value == c.mintFee, "support our artists, send eth"); if (c.mintFee > 0) { uint256 _controllerShare = msg.value.mul(p.controllerShare).div(1000); uint256 _artistRoyalty = msg.value.sub(_controllerShare); require(_artistRoyalty.add(_controllerShare) == msg.value, "problem with fee"); p.feesCollected = p.feesCollected.add(c.mintFee); pendingWithdrawals[controller] = pendingWithdrawals[controller].add(_controllerShare); pendingWithdrawals[p.artist] = pendingWithdrawals[p.artist].add(_artistRoyalty); } p.points[msg.sender] = p.points[msg.sender].sub(c.points); p.spentPineapples = p.spentPineapples.add(c.points); memeLtd.mint(msg.sender, card, 1, ""); emit Redeemed(msg.sender, pool, c.points); } function rescuePineapples(address account, uint256 pool) public poolExists(pool) updateReward(account, pool) returns (uint256) { require(msg.sender == rescuer, "!rescuer"); Pool storage p = pools[pool]; uint256 earnedPoints = p.points[account]; p.spentPineapples = p.spentPineapples.add(earnedPoints); p.points[account] = 0; // transfer remaining MEME to the account if (balanceOf(account, pool) > 0) { _rescuePineapples(account, pool); } emit Redeemed(account, pool, earnedPoints); return earnedPoints; } function setArtist(uint256 pool, address artist) public onlyOwner { uint256 amount = pendingWithdrawals[artist]; pendingWithdrawals[artist] = 0; pendingWithdrawals[artist] = pendingWithdrawals[artist].add(amount); pools[pool].artist = artist; emit UpdatedArtist(pool, artist); } function setController(address _controller) public onlyOwner { uint256 amount = pendingWithdrawals[controller]; pendingWithdrawals[controller] = 0; pendingWithdrawals[_controller] = pendingWithdrawals[_controller].add(amount); controller = _controller; } function setRescuer(address _rescuer) public onlyOwner { rescuer = _rescuer; } function setControllerShare(uint256 pool, uint256 _controllerShare) public onlyOwner poolExists(pool) { pools[pool].controllerShare = _controllerShare; } function addCard( uint256 pool, uint256 id, uint256 points, uint256 mintFee, uint256 releaseTime ) public onlyOwner poolExists(pool) { Card storage c = pools[pool].cards[id]; c.points = points; c.releaseTime = releaseTime; c.mintFee = mintFee; emit CardAdded(pool, id, points, mintFee, releaseTime); } function createCard( uint256 pool, uint256 supply, uint256 points, uint256 mintFee, uint256 releaseTime ) public onlyOwner poolExists(pool) returns (uint256) { uint256 tokenId = memeLtd.create(supply, 0, "", ""); require(tokenId > 0, "ERC1155 create did not succeed"); Card storage c = pools[pool].cards[tokenId]; c.points = points; c.releaseTime = releaseTime; c.mintFee = mintFee; emit CardAdded(pool, tokenId, points, mintFee, releaseTime); return tokenId; } function createPool( uint256 id, uint256 periodStart, uint256 controllerShare, address artist ) public onlyOwner returns (uint256) { require(pools[id].periodStart == 0, "pool exists"); Pool storage p = pools[id]; p.periodStart = periodStart; p.controllerShare = controllerShare; p.artist = artist; emit PoolAdded(id, artist, periodStart); } function withdrawFee() public { uint256 amount = pendingWithdrawals[msg.sender]; require(amount > 0, "nothing to withdraw"); pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } }
override PoolTokenWrapper's transfer() function
function transfer( uint256 fromPool, uint256 toPool, uint256 amount ) public poolExists(fromPool) poolExists(toPool) updateReward(msg.sender, fromPool) updateReward(msg.sender, toPool) whenNotPaused() { Pool memory toP = pools[toPool]; require(block.timestamp >= toP.periodStart, "pool not open"); super.transfer(fromPool, toPool, amount); emit Transferred(msg.sender, fromPool, toPool, amount); }
6,746,326
./full_match/1/0x17B00548003683C423eecce4371b4bA56eEd962b/sources/contracts/Dram.sol
Resumes the smart contract./
function unpause() external onlyRoleOrAdmin(REGULATORY_MANAGER_ROLE) { _unpause(); }
3,169,550
./full_match/1/0x80e3F8d00f36578B548A99f1Fd94C01bcfB0Db2B/sources/arbos-contracts/arbos/builtin/ArbSys.sol
Precompiled contract that exists in every Arbitrum chain at address(100), 0x0000000000000000000000000000000000000064. Exposes a variety of system-level functionality./
interface ArbSys { function arbOSVersion() external pure returns (uint); function arbChainID() external view returns(uint); function arbBlockNumber() external view returns (uint); function withdrawEth(address destination) external payable returns(uint); function sendTxToL1(address destination, bytes calldata calldataForL1) external payable returns(uint); function getTransactionCount(address account) external view returns(uint256); function getStorageAt(address account, uint256 index) external view returns (uint256); function isTopLevelCall() external view returns (bool); event EthWithdrawal(address indexed destAddr, uint amount); event L2ToL1Transaction(address caller, address indexed destination, uint indexed uniqueId, uint indexed batchNumber, uint indexInBatch, uint arbBlockNum, uint ethBlockNum, uint timestamp, uint callvalue, bytes data); }
4,897,234
./full_match/137/0xc2768beF7a6BB57F0FfA169a9ED4017c09696FF1/sources/contracts/Peronio.sol
Swaps USDC into MAI on QuickSwap pool
function _swapUSDCtoMAI(uint256 amount) internal returns (uint256 maiAmount) { address[] memory path = new address[](2); path[0] = USDC_ADDRESS; path[1] = MAI_ADDRESS; uint256[] memory amounts = IUniswapV2Router02(QUICKSWAP_ROUTER_ADDRESS) .swapExactTokensForTokens( amount, 1, path, address(this), block.timestamp + 3600 ); maiAmount = amounts[1]; }
4,717,819
./full_match/3/0xE1d2f3fcfcb8E29B60e0C20ea6c1506D9887a568/sources/contracts/oracle.sol
Returns the latest price/
function getThePrice() public view returns (uint256) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return uint256(price); }
8,121,220
./partial_match/42/0x8e79f54b30E788b9B7A50536C57311C41b2b413F/sources/HodlerPool.sol
_allStakers[msg.sender].rewardsBalance = 0;stakingToken.safeTransfer(msg.sender, reward);emit RewardPaid(msg.sender, trueReward);
function getReward(uint stakerLevel) public updateReward(msg.sender, stakerLevel) checkStart returns (uint256) { uint256 reward = earned(msg.sender, stakerLevel); if (reward > 0) { return reward; } else return 0; }
3,424,555
// Sources flattened with hardhat v2.1.1 https://hardhat.org // File contracts/interfaces/IERC20.sol pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IMaintainersRegistry.sol pragma solidity ^0.6.12; /** * IMaintainersRegistry contract. * @author Nikola Madjarevic * Date created: 8.5.21. * Github: madjarevicn */ interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); } // File contracts/system/HordUpgradable.sol pragma solidity ^0.6.12; /** * HordUpgradables contract. * @author Nikola Madjarevic * Date created: 8.5.21. * Github: madjarevicn */ contract HordUpgradable { address public hordCongress; IMaintainersRegistry public maintainersRegistry; // Only maintainer modifier modifier onlyMaintainer { require(maintainersRegistry.isMaintainer(msg.sender), "HordUpgradable: Restricted only to Maintainer"); _; } // Only chainport congress modifier modifier onlyHordCongress { require(msg.sender == hordCongress, "HordUpgradable: Restricted only to HordCongress"); _; } function setCongressAndMaintainers( address _hordCongress, address _maintainersRegistry ) internal { hordCongress = _hordCongress; maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } function setMaintainersRegistry( address _maintainersRegistry ) public onlyHordCongress { maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } } // File @openzeppelin/contracts/introspection/IERC165.sol@v3.4.1 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); } // File @openzeppelin/contracts/token/ERC1155/IERC1155.sol@v3.4.1 pragma solidity >=0.6.2 <0.8.0; /** * @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; } // File contracts/interfaces/IHordTicketFactory.sol pragma solidity ^0.6.12; /** * IHordTicketFactory contract. * @author Nikola Madjarevic * Date created: 11.5.21. * Github: madjarevicn */ interface IHordTicketFactory is IERC1155 { function getTokenSupply(uint tokenId) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol@v3.4.1 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v3.4.1 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/Initializable.sol@v3.4.1 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {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)); } } // File @openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155ReceiverUpgradeable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable { function __ERC1155Receiver_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); } function __ERC1155Receiver_init_unchained() internal initializer { _registerInterface( ERC1155ReceiverUpgradeable(address(0)).onERC1155Received.selector ^ ERC1155ReceiverUpgradeable(address(0)).onERC1155BatchReceived.selector ); } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable { function __ERC1155Holder_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); __ERC1155Holder_init_unchained(); } function __ERC1155Holder_init_unchained() internal initializer { } function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } uint256[50] private __gap; } // File contracts/libraries/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File contracts/HordTicketManager.sol pragma solidity 0.6.12; /** * HordTicketManager contract. * @author Nikola Madjarevic * Date created: 11.5.21. * Github: madjarevicn */ contract HordTicketManager is HordUpgradable, ERC1155HolderUpgradeable { using SafeMath for *; // Minimal time to stake in order to be eligible for claiming NFT uint256 public minTimeToStake; // Minimal amount to stake in order to be eligible for claiming NFT uint256 public minAmountToStake; // Token being staked IERC20 public stakingToken; // Factory of Hord tickets IHordTicketFactory public hordTicketFactory; // Mapping championId to tokenIds mapping (uint256 => uint256[]) internal championIdToMintedTokensIds; // Users stake struct UserStake { uint256 amountStaked; uint256 amountOfTicketsGetting; uint256 unlockingTime; bool isWithdrawn; } /// @dev Mapping user address to tokenId to stakes for that token mapping(address => mapping(uint => UserStake[])) public addressToTokenIdToStakes; // Count number of reserved tickets for tokenId mapping(uint256 => uint256) internal tokenIdToNumberOfTicketsReserved; event TokensStaked( address user, uint amountStaked, uint inFavorOfTokenId, uint numberOfTicketsReserved, uint unlockingTime ); event NFTsClaimed( address beneficiary, uint256 amountUnstaked, uint256 amountTicketsClaimed, uint tokenId ); function initialize( address _hordCongress, address _maintainersRegistry, address _stakingToken, uint256 _minTimeToStake, uint256 _minAmountToStake ) public initializer { // Set hord congress and maintainers registry setCongressAndMaintainers(_hordCongress, _maintainersRegistry); // Set staking token stakingToken = IERC20(_stakingToken); // Set minimal time to stake tokens minTimeToStake = _minTimeToStake; // Set minimal amount to stake minAmountToStake = _minAmountToStake; } /** * @notice Set hord ticket factory contract. After set first time, * can be changed only by HordCongress * @param _hordTicketFactory is the address of HordTicketFactory contract */ function setHordTicketFactory(address _hordTicketFactory) public { // Initial setting is allowed during deployment, after that only congress can change it if(address(hordTicketFactory) != address(0)) { require(msg.sender == hordCongress); } // Set hord ticket factory hordTicketFactory = IHordTicketFactory(_hordTicketFactory); } /** * @notice Set minimal time to stake, callable only by HordCongress * @param _minimalTimeToStake is minimal amount of time (seconds) user has to stake * staking token in order to be eligible to claim NFT */ function setMinTimeToStake( uint256 _minimalTimeToStake ) onlyHordCongress external { minTimeToStake = _minimalTimeToStake; } /** * @notice Set minimal amount to stake, callable only by HordCongress * @param _minimalAmountToStake is minimal amount of tokens (WEI) user has to stake * in order to be eligible to claim NFT */ function setMinAmountToStake( uint256 _minimalAmountToStake ) onlyHordCongress external { minAmountToStake = _minimalAmountToStake; } /** * @notice Map token id with champion id * @param tokenId is the ID of the token (representing token class / series) * @param championId is the ID of the champion */ function addNewTokenIdForChampion( uint tokenId, uint championId ) external { require(msg.sender == address(hordTicketFactory), "Only Hord Ticket factory can issue a call to this function"); // Push token Id to champion id championIdToMintedTokensIds[championId].push(tokenId); } /** * @notice Stake and reserve NFTs, per specific staking rules * @param tokenId is the ID of the token being staked (class == series) * @param numberOfTickets is representing how many NFTs of same series user wants to get */ function stakeAndReserveNFTs( uint tokenId, uint numberOfTickets ) public { // Get number of reserved tickets uint256 numberOfTicketsReserved = tokenIdToNumberOfTicketsReserved[tokenId]; // Check there's enough tickets to get require(numberOfTicketsReserved.add(numberOfTickets)<= hordTicketFactory.getTokenSupply(tokenId), "Not enough tickets to sell."); // Fixed stake per ticket uint amountOfTokensToStake = minAmountToStake.mul(numberOfTickets); // Transfer tokens from user stakingToken.transferFrom( msg.sender, address(this), amountOfTokensToStake ); UserStake memory userStake = UserStake({ amountStaked: amountOfTokensToStake, amountOfTicketsGetting: numberOfTickets, unlockingTime: minTimeToStake.add(block.timestamp), isWithdrawn: false }); addressToTokenIdToStakes[msg.sender][tokenId].push(userStake); // Increase number of tickets reserved tokenIdToNumberOfTicketsReserved[tokenId] = numberOfTicketsReserved.add(numberOfTickets); emit TokensStaked( msg.sender, amountOfTokensToStake, tokenId, numberOfTickets, userStake.unlockingTime ); } /** * @notice Function to claim NFTs and withdraw tokens staked for that NFTs * @param tokenId is representing token class for which user has performed stake */ function claimNFTs( uint tokenId, uint startIndex, uint endIndex ) public { UserStake [] storage userStakesForNft = addressToTokenIdToStakes[msg.sender][tokenId]; uint256 totalStakeToWithdraw; uint256 ticketsToWithdraw; uint256 i = startIndex; while (i < userStakesForNft.length && i < endIndex) { UserStake storage stake = userStakesForNft[i]; if(stake.isWithdrawn || stake.unlockingTime > block.timestamp) { i++; continue; } totalStakeToWithdraw = totalStakeToWithdraw.add(stake.amountStaked); ticketsToWithdraw = ticketsToWithdraw.add(stake.amountOfTicketsGetting); stake.isWithdrawn = true; i++; } if(totalStakeToWithdraw > 0 && ticketsToWithdraw > 0) { // Transfer staking tokens stakingToken.transfer(msg.sender, totalStakeToWithdraw); // Transfer NFTs hordTicketFactory.safeTransferFrom( address(this), msg.sender, tokenId, ticketsToWithdraw, "0x0" ); // Emit event emit NFTsClaimed( msg.sender, totalStakeToWithdraw, ticketsToWithdraw, tokenId ); } } /** * @notice Get number of specific tokens claimed * @param tokenId is the subject of search */ function getAmountOfTokensClaimed(uint tokenId) external view returns (uint256) { uint mintedSupply = hordTicketFactory.getTokenSupply(tokenId); return mintedSupply.sub(hordTicketFactory.balanceOf(address(this), tokenId)); } /** * @notice Get amount of tickets reserved for selected tokenId * @param tokenId is the subject of search */ function getAmountOfTicketsReserved( uint tokenId ) external view returns (uint256) { return tokenIdToNumberOfTicketsReserved[tokenId]; } /** * @notice Get account stakes for specified token Id * @param account is user address * @param tokenId is the id of the token in favor of which stake is made. */ function getUserStakesForTokenId( address account, uint tokenId ) external view returns ( uint256[] memory, uint256[] memory, uint256[] memory, bool[] memory ) { UserStake [] memory userStakes = addressToTokenIdToStakes[account][tokenId]; uint numberOfStakes = userStakes.length; uint256[] memory amountsStaked = new uint256[](numberOfStakes); uint256[] memory ticketsBought = new uint256[](numberOfStakes); uint256[] memory unlockingTimes = new uint256[](numberOfStakes); bool[] memory isWithdrawn = new bool[](numberOfStakes); for(uint i = 0; i < numberOfStakes; i++) { // Fulfill arrays with stake information amountsStaked[i] = userStakes[i].amountStaked; ticketsBought[i] = userStakes[i].amountOfTicketsGetting; unlockingTimes[i] = userStakes[i].unlockingTime; isWithdrawn[i] = userStakes[i].isWithdrawn; } return (amountsStaked, ticketsBought, unlockingTimes, isWithdrawn); } /** * @notice Get currently how many tokens is account actively staking * @param account is address for which stakes are being checked * @param tokenId is the subject of search for the passed account */ function getCurrentAmountStakedForTokenId( address account, uint tokenId ) external view returns (uint256) { UserStake [] memory userStakes = addressToTokenIdToStakes[account][tokenId]; uint numberOfStakes = userStakes.length; uint amountCurrentlyStaking = 0; for(uint i = 0; i < numberOfStakes; i++) { if(userStakes[i].isWithdrawn == false) { amountCurrentlyStaking = amountCurrentlyStaking.add(userStakes[i].amountStaked); } } return amountCurrentlyStaking; } /** * @notice Function to get all token ids minted for specific champion * @param championId is the db id of the champion */ function getChampionTokenIds( uint championId ) external view returns (uint[] memory) { return championIdToMintedTokensIds[championId]; } /** * @notice Function to get number of stakes for user and token * @param user is the address of selected user * @param tokenId is the ID of the token */ function getNumberOfStakesForUserAndToken( address user, uint tokenId ) external view returns (uint256) { return addressToTokenIdToStakes[user][tokenId].length; } }
Get amount of tickets reserved for selected tokenId tokenId is the subject of search/
function getAmountOfTicketsReserved( uint tokenId ) external view returns (uint256) { return tokenIdToNumberOfTicketsReserved[tokenId]; }
14,848,859
./full_match/1/0xEaa72cfBFA202E0100F9b2712D2C076a033925D6/sources/contracts/KreyptOrder.sol
/ Command start at 1 but array start at 0 Command start at 1 but array start at 0
function validateOrder(uint256 commandNb, string[] memory Uris) public onlyRole(MINTER_ROLE) { if (commandNb > commands.length || commandNb == 0) revert OrderNotFound(); Command memory command = commands[commandNb - 1]; if (command.status != Status.Pending) revert CommandNotPending(); commands[commandNb - 1].status = Status.Accepted; if (Uris.length != bundles[command.bundleNb].itemsSize) revert ErrorData(); for (uint i = 0; i < bundles[command.bundleNb].itemsSize;) { NFTType _kreyptNFT = bundles[command.bundleNb].items[i].kreyptNFT; commandIdToNftIds[commandNb].push(IKreyptNFT(kreyptNFTAddress[_kreyptNFT]).mint( command.owner, command.sentence, command.clearSentence, Uris[i] )); unchecked { ++i; } } if (amountTotal > 0) { if (!sent) revert FailedToTransfer(); } emit OrderValidated(command.id); } @param commandRejects : The array of the command number to reject @param refunds : An array of boolean to know if the buyer need to be refunded @param percentageFeeTake : An array of percentage to take from the buyer
9,740,080
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./ERC721Common.sol"; // To read more about NFTs, checkout the ERC721 standard: // https://eips.ethereum.org/EIPS/eip-721 /** * @title NFT * SimpleNFT - A concrete NFT contract implementation that can optionally inherit from several Mixins for added functionality or directly from ERC721Common for a barebones implementation. */ contract MichaelDeployedContract is ERC721Common { using Counters for Counters.Counter; Counters.Counter private _nextTokenId; /** * @dev Replace with your own unique name and symbol */ constructor() ERC721Common("MichaelDeployedContract", "MCD") { // nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter _nextTokenId.increment(); } function mint(address _to) public virtual returns (uint256) { uint256 currentTokenId = _nextTokenId.current(); _nextTokenId.increment(); _safeMint(_to, currentTokenId); return currentTokenId; } function baseTokenURI() public override pure returns (string memory) { return "https://creatures-api.opensea.io/api/creature/"; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title ERC721Common * ERC721Common - ERC721 contract with basic functionality and AccessControl */ abstract contract ERC721Common is ERC721, AccessControl { using SafeMath for uint256; constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol) { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Returns the base uri used for all the tokens */ function baseTokenURI() virtual public pure returns (string memory); /** * @dev Returns the tokenURI for the tokenId, which is just baseTokenURI + tokenId * @param _tokenId the tokenId */ function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * @dev verifies if the interfaceId passed in is supported * Must be implemented here due to Solidity limitations * @param interfaceId interface being supported */ function supportsInterface(bytes4 interfaceId) public virtual view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface 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; }
verifies if the interfaceId passed in is supported Must be implemented here due to Solidity limitations interfaceId interface being supported/
function supportsInterface(bytes4 interfaceId) public virtual view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); }
5,932,715
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@ieigen/anonmisc/contracts/PedersenCommitmentBabyJubjub.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./Marketplace.sol"; import "./pedersen_comm_babyjubjub_verifier.sol"; import "./range_proof_verifier.sol"; import "./pedersen_comm_plus_range_proof_verifier.sol"; import "hardhat/console.sol"; contract Bucketization is Marketplace { using Counters for Counters.Counter; Counters.Counter private _orderId; Counters.Counter private _pairId; PedersenCommitmentBabyJubjub _pc; PedersenCommBabyJubjubVerifier _pcVerifier; RangeProofVerifier _rfVerifier; PedersenCommPlusRangeProofVerifier _pcrfVerifier; uint256 constant private restrictedDealCount = 1; //mapping (address => uint256[3]) private _credits; // array[0] => r || array[1] => X || array[2] => Y mapping (address => uint256[2]) private _credits; mapping (address => uint256) private _dealTimes; struct UnmatchedOrder { uint id; address account; uint256 rateCommX; uint256 rateCommY; uint buyOrSell; // 0 BUY, 1 SELL } address payable private _marketplaceAccount; constructor(address payable marketplaceAccount) { _marketplaceAccount = marketplaceAccount; // to be comfired _pc = new PedersenCommitmentBabyJubjub(); _pc.setH(); _pcVerifier = new PedersenCommBabyJubjubVerifier(); _rfVerifier = new RangeProofVerifier(); _pcrfVerifier = new PedersenCommPlusRangeProofVerifier(); } UnmatchedOrder[] private _unmatchedOrders; mapping (uint => uint) private _orderIdToOrderIdx; mapping (uint => OrderPair) private _matchedPair; mapping (address => uint[]) private _buyerAddrToPairIds; // mapping (address => uint[]) private _sellerAddrToPairIds; function transferToMarketplace() payable public { payable(address(this)).transfer(msg.value); } function getBalance() public view returns (uint256) { return address(this).balance; } fallback() external payable {} receive() external payable {} function deposit(address account, /*uint256 r,*/uint256 commX, uint256 commY) public { if (_credits[account][0] == 0 && _credits[account][1] == 0) { _credits[account][0] = commX; _credits[account][1] = commY; } else { (, _credits[account][0], _credits[account][1]) = _pc.addCommitment(0, _credits[account][0], _credits[account][1], 0, commX, commY); } } function withdraw(address trader, uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[5] memory input) public payable { // input[0] => hx input[1] => hy input[2] => v input[3] => commx input[4] => commy require(msg.sender == trader, "B: invalid withdraw address"); // Restrict users to withdraw cash after a certain number of deal. require(_dealTimes[trader] >= restrictedDealCount, "B: not enough deal time"); require(_pcVerifier.verifyProof(a, b, c, input), "B: invalid proof"); require(_credits[trader][0] > 0 && _credits[trader][1] > 0, "B: account has no assets"); require(_credits[trader][0] == input[3] && _credits[trader][1] == input[4], "B:invalid pedersen comm"); (bool success, ) = trader.call{value: input[2]}(""); require(success, "Transfer failed."); delete _credits[trader]; } // 3.1-3.4 function submitOrder(address account, uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[7] memory input, uint256 rateCommX, uint256 rateCommY, uint kind) public returns(uint) { require(_pcrfVerifier.verifyProof(a, b, c, input), "B:invalid proof"); require(_credits[account][0] == input[2] && _credits[account][1] == input[3], "B:invalid pedersen comm"); _orderId.increment(); uint256 id = _orderId.current(); _orderIdToOrderIdx[id] = _unmatchedOrders.length; _unmatchedOrders.push(UnmatchedOrder(id, account, rateCommX, rateCommY, kind)); return uint(id); } // 3.10-3.12 function attachOrderBook(uint id, Bucket memory bucket, uint[2] memory a, uint[2][2] memory b, uint[2] memory c) public { UnmatchedOrder memory order = _unmatchedOrders[_orderIdToOrderIdx[id]]; uint[2] memory input = [bucket.startValue, bucket.startValue + bucket.width]; // check the bucket including the rateComm require(_rfVerifier.verifyProof(a, b, c, input), "B: Invalid range proof"); // TODO check the rateComm is exactly from order id if (order.buyOrSell == 0) { BuyOrders.push(Order(id, order.account, 0, order.rateCommX, order.rateCommY, bucket)); } else { SellOrders.push(Order(id, order.account, 1, order.rateCommX, order.rateCommY, bucket)); } } // 3.14-3.15 function tradeRound() public { Order[] memory sortedSell = sort(SellOrders); Order[] memory sortedBuy = sort(BuyOrders); OrderPair[] memory matchedPair = matching(sortedBuy, sortedSell); for (uint i = 0; i < matchedPair.length; i ++) { _pairId.increment(); _matchedPair[_pairId.current()] = matchedPair[i]; _buyerAddrToPairIds[matchedPair[i].buyOrder.trader].push(_pairId.current()); _sellerAddrToPairIds[matchedPair[i].sellOrder.trader].push(_pairId.current()); // TODO pop the matched buy orders and sell orders } } function findMatchedSeller(uint orderId, address buyerAddr) public view returns (address, int) { for (uint i = 0; i < _buyerAddrToPairIds[buyerAddr].length; i++) { uint pairId = _buyerAddrToPairIds[buyerAddr][i]; OrderPair memory op = _matchedPair[pairId]; if (op.buyOrder.id == orderId) { return (op.sellOrder.trader, int(pairId)); } } // find nothing return (address(0), -1); } function findMatchedBuyer(uint orderId, address sellerAddr) public view returns (address, int) { for (uint i = 0; i < _sellerAddrToPairIds[sellerAddr].length; i++) { uint pairId = _sellerAddrToPairIds[sellerAddr][i]; OrderPair memory op = _matchedPair[pairId]; if (op.sellOrder.id == orderId) { return (op.buyOrder.trader, int(pairId)); } } // find nothing return (address(0), -1); } function findPair(address seller) public view returns (uint) { for (uint i = 0; i < _buyerAddrToPairIds[msg.sender].length; i ++) { uint pairId = _buyerAddrToPairIds[msg.sender][i]; OrderPair memory op = _matchedPair[pairId]; if (op.sellOrder.trader == seller) { return pairId; } } // doesn't not match ever return 0; } // 3.17-3.22 function confirmRound(/*uint256 r1, uint256 r2,*/uint256 fees, uint256 proofX, uint256 proofY, uint pairId, uint256 hx, uint256 hy) public payable { OrderPair memory pair = _matchedPair[pairId]; // TODO check pair //uint256 r3; uint256 feeCommX; uint256 feeCommY; (, feeCommX, feeCommY) = _pc.subCommitment(0, pair.buyOrder.rateCommX, pair.buyOrder.rateCommY, 0, pair.sellOrder.rateCommX, pair.sellOrder.rateCommY); require(feeCommX == proofX && feeCommY == proofY, "B: Invalid fee comm"); //require(_pc.verifyWithH(r3, fees, feeCommX, feeCommY, hx, hy), "B: Verify commitment failed"); debit(pair.buyOrder.trader, /*r1,*/ pair.buyOrder.rateCommX, pair.buyOrder.rateCommY); credit(pair.sellOrder.trader, /*r2,*/ pair.sellOrder.rateCommX, pair.sellOrder.rateCommY); _dealTimes[pair.buyOrder.trader] += 1; _dealTimes[pair.sellOrder.trader] += 1; (bool success, ) = _marketplaceAccount.call{value: fees}(""); require(success, "Transfer failed."); delete _matchedPair[pairId]; uint len = _buyerAddrToPairIds[pair.buyOrder.trader].length - 1; for (uint i = 0; i < len; i ++) { if (pairId == _buyerAddrToPairIds[pair.buyOrder.trader][i]) { _buyerAddrToPairIds[pair.buyOrder.trader][i] = _buyerAddrToPairIds[pair.buyOrder.trader][len]; } } _buyerAddrToPairIds[pair.buyOrder.trader].pop(); len = _sellerAddrToPairIds[pair.sellOrder.trader].length - 1; for (uint i = 0; i < len; i ++) { if (pairId == _sellerAddrToPairIds[pair.sellOrder.trader][i]) { _sellerAddrToPairIds[pair.sellOrder.trader][i] = _sellerAddrToPairIds[pair.sellOrder.trader][len]; } } _sellerAddrToPairIds[pair.sellOrder.trader].pop(); } function debit(address trader, /*uint256 r,*/ uint256 commX, uint256 commY) internal { (, _credits[trader][0], _credits[trader][1]) = _pc.subCommitment(0, _credits[trader][0], _credits[trader][1], 0, commX, commY); } function credit(address trader, /*uint256 r,*/ uint256 commX, uint256 commY) internal { (, _credits[trader][0], _credits[trader][1]) = _pc.addCommitment(0, _credits[trader][0], _credits[trader][1], 0, commX, commY); } }
3.10-3.12 check the bucket including the rateComm TODO check the rateComm is exactly from order id
function attachOrderBook(uint id, Bucket memory bucket, uint[2] memory a, uint[2][2] memory b, uint[2] memory c) public { UnmatchedOrder memory order = _unmatchedOrders[_orderIdToOrderIdx[id]]; uint[2] memory input = [bucket.startValue, bucket.startValue + bucket.width]; require(_rfVerifier.verifyProof(a, b, c, input), "B: Invalid range proof"); if (order.buyOrSell == 0) { BuyOrders.push(Order(id, order.account, 0, order.rateCommX, order.rateCommY, bucket)); SellOrders.push(Order(id, order.account, 1, order.rateCommX, order.rateCommY, bucket)); } }
1,755,850
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) 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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); 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. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Cash Telex * @dev Assets Backed ERC20 Token , where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract CashTelex is StandardToken { string public constant name = "Cash Telex"; string public constant symbol = "CTLX"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 800000000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function CashTelex() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } }
Constructor that gives msg.sender all of existing tokens./
function CashTelex() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
15,066,841
// File: contracts/zeppelin/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @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; } } // File: contracts/USDPImplementationV3.sol pragma solidity ^0.4.24; pragma experimental "v0.5.0"; /** * @title USDPImplementationV3 * @dev this contract is a Pausable ERC20 token with Burn and Mint * controlled by a central SupplyController. By implementing USDPImplementation * this contract also includes external methods for setting * a new implementation contract for the Proxy. * NOTE: The storage defined here will actually be held in the Proxy * contract and all calls to this contract should be made through * the proxy, including admin actions done as owner or supplyController. * Any call to transfer against this contract should fail * with insufficient funds since no tokens will be issued there. */ contract USDPImplementationV3 { /** * MATH */ using SafeMath for uint256; /** * DATA */ // INITIALIZATION DATA bool private initialized = false; // ERC20 BASIC DATA mapping(address => uint256) internal balances; uint256 internal totalSupply_; string public constant name = "Pax Dollar"; // solium-disable-line string public constant symbol = "USDP"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase // ERC20 DATA mapping(address => mapping(address => uint256)) internal allowed; // OWNER DATA PART 1 address public owner; // PAUSABILITY DATA bool public paused = false; // ASSET PROTECTION DATA address public assetProtectionRole; mapping(address => bool) internal frozen; // SUPPLY CONTROL DATA address public supplyController; // OWNER DATA PART 2 address public proposedOwner; // DELEGATED TRANSFER DATA address public betaDelegateWhitelister; mapping(address => bool) internal betaDelegateWhitelist; mapping(address => uint256) internal nextSeqs; // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256( "EIP712Domain(string name,address verifyingContract)" ); bytes32 constant internal EIP712_DELEGATED_TRANSFER_SCHEMA_HASH = keccak256( "BetaDelegatedTransfer(address to,uint256 value,uint256 fee,uint256 seq,uint256 deadline)" ); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; /** * EVENTS */ // ERC20 BASIC EVENTS event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 EVENTS event Approval( address indexed owner, address indexed spender, uint256 value ); // OWNABLE EVENTS event OwnershipTransferProposed( address indexed currentOwner, address indexed proposedOwner ); event OwnershipTransferDisregarded( address indexed oldProposedOwner ); event OwnershipTransferred( address indexed oldOwner, address indexed newOwner ); // PAUSABLE EVENTS event Pause(); event Unpause(); // ASSET PROTECTION EVENTS event AddressFrozen(address indexed addr); event AddressUnfrozen(address indexed addr); event FrozenAddressWiped(address indexed addr); event AssetProtectionRoleSet ( address indexed oldAssetProtectionRole, address indexed newAssetProtectionRole ); // SUPPLY CONTROL EVENTS event SupplyIncreased(address indexed to, uint256 value); event SupplyDecreased(address indexed from, uint256 value); event SupplyControllerSet( address indexed oldSupplyController, address indexed newSupplyController ); // DELEGATED TRANSFER EVENTS event BetaDelegatedTransfer( address indexed from, address indexed to, uint256 value, uint256 seq, uint256 fee ); event BetaDelegateWhitelisterSet( address indexed oldWhitelister, address indexed newWhitelister ); event BetaDelegateWhitelisted(address indexed newDelegate); event BetaDelegateUnwhitelisted(address indexed oldDelegate); /** * FUNCTIONALITY */ // INITIALIZATION FUNCTIONALITY /** * @dev sets 0 initials tokens, the owner, and the supplyController. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */ function initialize() public { require(!initialized, "already initialized"); owner = msg.sender; assetProtectionRole = address(0); totalSupply_ = 0; supplyController = msg.sender; initialized = true; } /** * The constructor is used here to ensure that the implementation * contract is initialized. An uncontrolled implementation * contract might lead to misleading state * for users who accidentally interact with it. */ constructor() public { initialize(); pause(); // Added in V2 initializeDomainSeparator(); } /** * @dev To be called when upgrading the contract using upgradeAndCall to add delegated transfers */ function initializeDomainSeparator() public { // hash the name context with the contract address EIP712_DOMAIN_HASH = keccak256(abi.encodePacked(// solium-disable-line EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(name)), bytes32(address(this)) )); proposedOwner = address(0); } // ERC20 BASIC FUNCTIONALITY /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token to a specified address from msg.sender * Note: the use of Safemath ensures that _value is nonnegative. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[msg.sender], "address frozen"); require(_value <= balances[msg.sender], "insufficient funds"); 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 _addr The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _addr) public view returns (uint256) { return balances[_addr]; } // ERC20 FUNCTIONALITY /** * @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 whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen"); require(_value <= balances[_from], "insufficient funds"); require(_value <= allowed[_from][msg.sender], "insufficient 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) public whenNotPaused returns (bool) { require(!frozen[_spender] && !frozen[msg.sender], "address frozen"); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } // OWNER FUNCTIONALITY /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "onlyOwner"); _; } /** * @dev Allows the current owner to begin transferring control of the contract to a proposedOwner * @param _proposedOwner The address to transfer ownership to. */ function proposeOwner(address _proposedOwner) public onlyOwner { require(_proposedOwner != address(0), "cannot transfer ownership to address zero"); require(msg.sender != _proposedOwner, "caller already is owner"); proposedOwner = _proposedOwner; emit OwnershipTransferProposed(owner, proposedOwner); } /** * @dev Allows the current owner or proposed owner to cancel transferring control of the contract to a proposedOwner */ function disregardProposeOwner() public { require(msg.sender == proposedOwner || msg.sender == owner, "only proposedOwner or owner"); require(proposedOwner != address(0), "can only disregard a proposed owner that was previously set"); address _oldProposedOwner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferDisregarded(_oldProposedOwner); } /** * @dev Allows the proposed owner to complete transferring control of the contract to the proposedOwner. */ function claimOwnership() public { require(msg.sender == proposedOwner, "onlyProposedOwner"); address _oldOwner = owner; owner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferred(_oldOwner, owner); } /** * @dev Reclaim all USDP at the contract address. * This sends the USDP tokens that this contract add holding to the owner. * Note: this is not affected by freeze constraints. */ function reclaimUSDP() external onlyOwner { uint256 _balance = balances[this]; balances[this] = 0; balances[owner] = balances[owner].add(_balance); emit Transfer(this, owner, _balance); } // PAUSABILITY FUNCTIONALITY /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "whenNotPaused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { require(!paused, "already paused"); paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { require(paused, "already unpaused"); paused = false; emit Unpause(); } // ASSET PROTECTION FUNCTIONALITY /** * @dev Sets a new asset protection role address. * @param _newAssetProtectionRole The new address allowed to freeze/unfreeze addresses and seize their tokens. */ function setAssetProtectionRole(address _newAssetProtectionRole) public { require(msg.sender == assetProtectionRole || msg.sender == owner, "only assetProtectionRole or Owner"); emit AssetProtectionRoleSet(assetProtectionRole, _newAssetProtectionRole); assetProtectionRole = _newAssetProtectionRole; } modifier onlyAssetProtectionRole() { require(msg.sender == assetProtectionRole, "onlyAssetProtectionRole"); _; } /** * @dev Freezes an address balance from being transferred. * @param _addr The new address to freeze. */ function freeze(address _addr) public onlyAssetProtectionRole { require(!frozen[_addr], "address already frozen"); frozen[_addr] = true; emit AddressFrozen(_addr); } /** * @dev Unfreezes an address balance allowing transfer. * @param _addr The new address to unfreeze. */ function unfreeze(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address already unfrozen"); frozen[_addr] = false; emit AddressUnfrozen(_addr); } /** * @dev Wipes the balance of a frozen address, burning the tokens * and setting the approval to zero. * @param _addr The new frozen address to wipe. */ function wipeFrozenAddress(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = balances[_addr]; balances[_addr] = 0; totalSupply_ = totalSupply_.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecreased(_addr, _balance); emit Transfer(_addr, address(0), _balance); } /** * @dev Gets whether the address is currently frozen. * @param _addr The address to check if frozen. * @return A bool representing whether the given address is frozen. */ function isFrozen(address _addr) public view returns (bool) { return frozen[_addr]; } // SUPPLY CONTROL FUNCTIONALITY /** * @dev Sets a new supply controller address. * @param _newSupplyController The address allowed to burn/mint tokens to control supply. */ function setSupplyController(address _newSupplyController) public { require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner"); require(_newSupplyController != address(0), "cannot set supply controller to address zero"); emit SupplyControllerSet(supplyController, _newSupplyController); supplyController = _newSupplyController; } modifier onlySupplyController() { require(msg.sender == supplyController, "onlySupplyController"); _; } /** * @dev Increases the total supply by minting the specified number of tokens to the supply controller account. * @param _value The number of tokens to add. * @return A boolean that indicates if the operation was successful. */ function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) { totalSupply_ = totalSupply_.add(_value); balances[supplyController] = balances[supplyController].add(_value); emit SupplyIncreased(supplyController, _value); emit Transfer(address(0), supplyController, _value); return true; } /** * @dev Decreases the total supply by burning the specified number of tokens from the supply controller account. * @param _value The number of tokens to remove. * @return A boolean that indicates if the operation was successful. */ function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; } // DELEGATED TRANSFER FUNCTIONALITY /** * @dev returns the next seq for a target address. * The transactor must submit nextSeqOf(transactor) in the next transaction for it to be valid. * Note: that the seq context is specific to this smart contract. * @param target The target address. * @return the seq. */ // function nextSeqOf(address target) public view returns (uint256) { return nextSeqs[target]; } /** * @dev Performs a transfer on behalf of the from address, identified by its signature on the delegatedTransfer msg. * Splits a signature byte array into r,s,v for convenience. * @param sig the signature of the delgatedTransfer msg. * @param to The address to transfer to. * @param value The amount to be transferred. * @param fee an optional ERC20 fee paid to the executor of betaDelegatedTransfer by the from address. * @param seq a sequencing number included by the from address specific to this contract to protect from replays. * @param deadline a block number after which the pre-signed transaction has expired. * @return A boolean that indicates if the operation was successful. */ function betaDelegatedTransfer( bytes sig, address to, uint256 value, uint256 fee, uint256 seq, uint256 deadline ) public returns (bool) { require(sig.length == 65, "signature should have length 65"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } require(_betaDelegatedTransfer(r, s, v, to, value, fee, seq, deadline), "failed transfer"); return true; } /** * @dev Performs a transfer on behalf of the from address, identified by its signature on the betaDelegatedTransfer msg. * Note: both the delegate and transactor sign in the fees. The transactor, however, * has no control over the gas price, and therefore no control over the transaction time. * Beta prefix chosen to avoid a name clash with an emerging standard in ERC865 or elsewhere. * Internal to the contract - see betaDelegatedTransfer and betaDelegatedTransferBatch. * @param r the r signature of the delgatedTransfer msg. * @param s the s signature of the delgatedTransfer msg. * @param v the v signature of the delgatedTransfer msg. * @param to The address to transfer to. * @param value The amount to be transferred. * @param fee an optional ERC20 fee paid to the delegate of betaDelegatedTransfer by the from address. * @param seq a sequencing number included by the from address specific to this contract to protect from replays. * @param deadline a block number after which the pre-signed transaction has expired. * @return A boolean that indicates if the operation was successful. */ function _betaDelegatedTransfer( bytes32 r, bytes32 s, uint8 v, address to, uint256 value, uint256 fee, uint256 seq, uint256 deadline ) internal whenNotPaused returns (bool) { require(betaDelegateWhitelist[msg.sender], "Beta feature only accepts whitelisted delegates"); require(value > 0 || fee > 0, "cannot transfer zero tokens with zero fee"); require(block.number <= deadline, "transaction expired"); // prevent sig malleability from ecrecover() require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "signature incorrect"); require(v == 27 || v == 28, "signature incorrect"); // EIP712 scheme: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md bytes32 delegatedTransferHash = keccak256(abi.encodePacked(// solium-disable-line EIP712_DELEGATED_TRANSFER_SCHEMA_HASH, bytes32(to), value, fee, seq, deadline )); bytes32 hash = keccak256(abi.encodePacked(EIP191_HEADER, EIP712_DOMAIN_HASH, delegatedTransferHash)); address _from = ecrecover(hash, v, r, s); require(_from != address(0), "error determining from address from signature"); require(to != address(0), "canno use address zero"); require(!frozen[to] && !frozen[_from] && !frozen[msg.sender], "address frozen"); require(value.add(fee) <= balances[_from], "insufficient fund"); require(nextSeqs[_from] == seq, "incorrect seq"); nextSeqs[_from] = nextSeqs[_from].add(1); balances[_from] = balances[_from].sub(value.add(fee)); if (fee != 0) { balances[msg.sender] = balances[msg.sender].add(fee); emit Transfer(_from, msg.sender, fee); } balances[to] = balances[to].add(value); emit Transfer(_from, to, value); emit BetaDelegatedTransfer(_from, to, value, seq, fee); return true; } /** * @dev Performs an atomic batch of transfers on behalf of the from addresses, identified by their signatures. * Lack of nested array support in arguments requires all arguments to be passed as equal size arrays where * delegated transfer number i is the combination of all arguments at index i * @param r the r signatures of the delgatedTransfer msg. * @param s the s signatures of the delgatedTransfer msg. * @param v the v signatures of the delgatedTransfer msg. * @param to The addresses to transfer to. * @param value The amounts to be transferred. * @param fee optional ERC20 fees paid to the delegate of betaDelegatedTransfer by the from address. * @param seq sequencing numbers included by the from address specific to this contract to protect from replays. * @param deadline block numbers after which the pre-signed transactions have expired. * @return A boolean that indicates if the operation was successful. */ function betaDelegatedTransferBatch( bytes32[] r, bytes32[] s, uint8[] v, address[] to, uint256[] value, uint256[] fee, uint256[] seq, uint256[] deadline ) public returns (bool) { require(r.length == s.length && r.length == v.length && r.length == to.length && r.length == value.length, "length mismatch"); require(r.length == fee.length && r.length == seq.length && r.length == deadline.length, "length mismatch"); for (uint i = 0; i < r.length; i++) { require( _betaDelegatedTransfer(r[i], s[i], v[i], to[i], value[i], fee[i], seq[i], deadline[i]), "failed transfer" ); } return true; } /** * @dev Gets whether the address is currently whitelisted for betaDelegateTransfer. * @param _addr The address to check if whitelisted. * @return A bool representing whether the given address is whitelisted. */ function isWhitelistedBetaDelegate(address _addr) public view returns (bool) { return betaDelegateWhitelist[_addr]; } /** * @dev Sets a new betaDelegate whitelister. * @param _newWhitelister The address allowed to whitelist betaDelegates. */ function setBetaDelegateWhitelister(address _newWhitelister) public { require(msg.sender == betaDelegateWhitelister || msg.sender == owner, "only Whitelister or Owner"); betaDelegateWhitelister = _newWhitelister; emit BetaDelegateWhitelisterSet(betaDelegateWhitelister, _newWhitelister); } modifier onlyBetaDelegateWhitelister() { require(msg.sender == betaDelegateWhitelister, "onlyBetaDelegateWhitelister"); _; } /** * @dev Whitelists an address to allow calling BetaDelegatedTransfer. * @param _addr The new address to whitelist. */ function whitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister { require(!betaDelegateWhitelist[_addr], "delegate already whitelisted"); betaDelegateWhitelist[_addr] = true; emit BetaDelegateWhitelisted(_addr); } /** * @dev Unwhitelists an address to disallow calling BetaDelegatedTransfer. * @param _addr The new address to whitelist. */ function unwhitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister { require(betaDelegateWhitelist[_addr], "delegate not whitelisted"); betaDelegateWhitelist[_addr] = false; emit BetaDelegateUnwhitelisted(_addr); } }
Performs a transfer on behalf of the from address, identified by its signature on the delegatedTransfer msg. Splits a signature byte array into r,s,v for convenience. sig the signature of the delgatedTransfer msg. to The address to transfer to. value The amount to be transferred. fee an optional ERC20 fee paid to the executor of betaDelegatedTransfer by the from address. seq a sequencing number included by the from address specific to this contract to protect from replays. deadline a block number after which the pre-signed transaction has expired. return A boolean that indicates if the operation was successful./
function betaDelegatedTransfer( bytes sig, address to, uint256 value, uint256 fee, uint256 seq, uint256 deadline ) public returns (bool) { require(sig.length == 65, "signature should have length 65"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } require(_betaDelegatedTransfer(r, s, v, to, value, fee, seq, deadline), "failed transfer"); return true; }
455,881
./partial_match/3/0xE333bacb250b1aDC74074d4DBf13662c6Bd96172/sources/GoldenGoose.sol
time calculator for locked tokens/
function addLockingTime(address lockingAddress,uint256 lockingTime, uint256 amount) internal returns (bool){ time[lockingAddress] = now + (lockingTime * 1 days); _lockedAmount[lockingAddress] = _lockedAmount[lockingAddress].add(amount); return true; }
5,077,810
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../access/Ownable.sol"; import "./TransparentUpgradeableProxy.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // 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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract 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 () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; interface IOneStepProof { // Bridges is sequencer bridge then delayed bridge function executeStep( address[2] calldata bridges, uint256 initialMessagesRead, bytes32[2] calldata accs, bytes calldata proof, bytes calldata bproof ) external view returns ( uint64 gas, uint256 afterMessagesRead, bytes32[4] memory fields ); function executeStepDebug( address[2] calldata bridges, uint256 initialMessagesRead, bytes32[2] calldata accs, bytes calldata proof, bytes calldata bproof ) external view returns (string memory startMachine, string memory afterMachine); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; library Messages { function messageHash( uint8 kind, address sender, uint256 blockNumber, uint256 timestamp, uint256 inboxSeqNum, uint256 gasPriceL1, bytes32 messageDataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( kind, sender, blockNumber, timestamp, inboxSeqNum, gasPriceL1, messageDataHash ) ); } function addMessageToInbox(bytes32 inbox, bytes32 message) internal pure returns (bytes32) { return keccak256(abi.encodePacked(inbox, message)); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface IBridge { event MessageDelivered( uint256 indexed messageIndex, bytes32 indexed beforeInboxAcc, address inbox, uint8 kind, address sender, bytes32 messageDataHash ); function deliverMessageToInbox( uint8 kind, address sender, bytes32 messageDataHash ) external payable returns (uint256); function executeCall( address destAddr, uint256 amount, bytes calldata data ) external returns (bool success, bytes memory returnData); // These are only callable by the admin function setInbox(address inbox, bool enabled) external; function setOutbox(address inbox, bool enabled) external; // View functions function activeOutbox() external view returns (address); function allowedInboxes(address inbox) external view returns (bool); function allowedOutboxes(address outbox) external view returns (bool); function inboxAccs(uint256 index) external view returns (bytes32); function messageCount() external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface IMessageProvider { event InboxMessageDelivered(uint256 indexed messageNum, bytes data); event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface IOutbox { event OutboxEntryCreated( uint256 indexed batchNum, uint256 outboxIndex, bytes32 outputRoot, uint256 numInBatch ); event OutBoxTransactionExecuted( address indexed destAddr, address indexed l2Sender, uint256 indexed outboxIndex, uint256 transactionIndex ); function l2ToL1Sender() external view returns (address); function l2ToL1Block() external view returns (uint256); function l2ToL1EthBlock() external view returns (uint256); function l2ToL1Timestamp() external view returns (uint256); function processOutgoingMessages(bytes calldata sendsData, uint256[] calldata sendLengths) external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface ISequencerInbox { event SequencerBatchDelivered( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, bytes32 afterAcc, bytes transactions, uint256[] lengths, uint256[] sectionsMetadata, uint256 seqBatchIndex, address sequencer ); event SequencerBatchDeliveredFromOrigin( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, bytes32 afterAcc, uint256 seqBatchIndex ); event DelayedInboxForced( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, uint256 totalDelayedMessagesRead, bytes32[2] afterAccAndDelayed, uint256 seqBatchIndex ); event SequencerAddressUpdated(address newAddress); function setSequencer(address newSequencer) external; function messageCount() external view returns (uint256); function maxDelayBlocks() external view returns (uint256); function maxDelaySeconds() external view returns (uint256); function inboxAccs(uint256 index) external view returns (bytes32); function proveBatchContainsSequenceNumber(bytes calldata proof, uint256 inboxCount) external view returns (uint256, bytes32); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../libraries/MerkleLib.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library ChallengeLib { using SafeMath for uint256; function firstSegmentSize(uint256 totalCount, uint256 bisectionCount) internal pure returns (uint256) { return totalCount / bisectionCount + (totalCount % bisectionCount); } function otherSegmentSize(uint256 totalCount, uint256 bisectionCount) internal pure returns (uint256) { return totalCount / bisectionCount; } function bisectionChunkHash( uint256 _segmentStart, uint256 _segmentLength, bytes32 _startHash, bytes32 _endHash ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_segmentStart, _segmentLength, _startHash, _endHash)); } function inboxDeltaHash(bytes32 _inboxAcc, bytes32 _deltaAcc) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_inboxAcc, _deltaAcc)); } function assertionHash(uint256 _arbGasUsed, bytes32 _restHash) internal pure returns (bytes32) { // Note: make sure this doesn't return Challenge.UNREACHABLE_ASSERTION (currently 0) return keccak256(abi.encodePacked(_arbGasUsed, _restHash)); } function assertionRestHash( uint256 _totalMessagesRead, bytes32 _machineState, bytes32 _sendAcc, uint256 _sendCount, bytes32 _logAcc, uint256 _logCount ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _totalMessagesRead, _machineState, _sendAcc, _sendCount, _logAcc, _logCount ) ); } function updatedBisectionRoot( bytes32[] memory _chainHashes, uint256 _challengedSegmentStart, uint256 _challengedSegmentLength ) internal pure returns (bytes32) { uint256 bisectionCount = _chainHashes.length - 1; bytes32[] memory hashes = new bytes32[](bisectionCount); uint256 chunkSize = ChallengeLib.firstSegmentSize(_challengedSegmentLength, bisectionCount); uint256 segmentStart = _challengedSegmentStart; hashes[0] = ChallengeLib.bisectionChunkHash( segmentStart, chunkSize, _chainHashes[0], _chainHashes[1] ); segmentStart = segmentStart.add(chunkSize); chunkSize = ChallengeLib.otherSegmentSize(_challengedSegmentLength, bisectionCount); for (uint256 i = 1; i < bisectionCount; i++) { hashes[i] = ChallengeLib.bisectionChunkHash( segmentStart, chunkSize, _chainHashes[i], _chainHashes[i + 1] ); segmentStart = segmentStart.add(chunkSize); } return MerkleLib.generateRoot(hashes); } function verifySegmentProof( bytes32 challengeState, bytes32 item, bytes32[] calldata _merkleNodes, uint256 _merkleRoute ) internal pure returns (bool) { return challengeState == MerkleLib.calculateRoot(_merkleNodes, _merkleRoute, item); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; import "../arch/IOneStepProof.sol"; interface IChallenge { function initializeChallenge( IOneStepProof[] calldata _executors, address _resultReceiver, bytes32 _executionHash, uint256 _maxMessageCount, address _asserter, address _challenger, uint256 _asserterTimeLeft, uint256 _challengerTimeLeft, ISequencerInbox _sequencerBridge, IBridge _delayedBridge ) external; function currentResponderTimeLeft() external view returns (uint256); function lastMoveBlock() external view returns (uint256); function timeout() external; function asserter() external view returns (address); function challenger() external view returns (address); function clearChallenge() external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; interface IChallengeFactory { function createChallenge( address _resultReceiver, bytes32 _executionHash, uint256 _maxMessageCount, address _asserter, address _challenger, uint256 _asserterTimeLeft, uint256 _challengerTimeLeft, ISequencerInbox _sequencerBridge, IBridge _delayedBridge ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./ICloneable.sol"; contract Cloneable is ICloneable { string private constant NOT_CLONE = "NOT_CLONE"; bool private isMasterCopy; constructor() public { isMasterCopy = true; } function isMaster() external view override returns (bool) { return isMasterCopy; } function safeSelfDestruct(address payable dest) internal { require(!isMasterCopy, NOT_CLONE); selfdestruct(dest); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface ICloneable { function isMaster() external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; library MerkleLib { function generateRoot(bytes32[] memory _hashes) internal pure returns (bytes32) { bytes32[] memory prevLayer = _hashes; while (prevLayer.length > 1) { bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2); for (uint256 i = 0; i < nextLayer.length; i++) { if (2 * i + 1 < prevLayer.length) { nextLayer[i] = keccak256( abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1]) ); } else { nextLayer[i] = prevLayer[2 * i]; } } prevLayer = nextLayer; } return prevLayer[0]; } function calculateRoot( bytes32[] memory nodes, uint256 route, bytes32 item ) internal pure returns (bytes32) { uint256 proofItems = nodes.length; require(proofItems <= 256); bytes32 h = item; for (uint256 i = 0; i < proofItems; i++) { if (route % 2 == 0) { h = keccak256(abi.encodePacked(nodes[i], h)); } else { h = keccak256(abi.encodePacked(h, nodes[i])); } route /= 2; } return h; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface INode { function initialize( address _rollup, bytes32 _stateHash, bytes32 _challengeHash, bytes32 _confirmData, uint256 _prev, uint256 _deadlineBlock ) external; function destroy() external; function addStaker(address staker) external returns (uint256); function removeStaker(address staker) external; function childCreated(uint256) external; function resetChildren() external; function newChildConfirmDeadline(uint256 deadline) external; function stateHash() external view returns (bytes32); function challengeHash() external view returns (bytes32); function confirmData() external view returns (bytes32); function prev() external view returns (uint256); function deadlineBlock() external view returns (uint256); function noChildConfirmedBeforeBlock() external view returns (uint256); function stakerCount() external view returns (uint256); function stakers(address staker) external view returns (bool); function firstChildBlock() external view returns (uint256); function latestChildNumber() external view returns (uint256); function requirePastDeadline() external view; function requirePastChildConfirmDeadline() external view; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface INodeFactory { function createNode( bytes32 _stateHash, bytes32 _challengeHash, bytes32 _confirmData, uint256 _prev, uint256 _deadlineBlock ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./INode.sol"; interface IRollupCore { function _stakerMap(address stakerAddress) external view returns ( uint256, uint256, uint256, address, bool ); function getNode(uint256 nodeNum) external view returns (INode); /** * @notice Get the address of the staker at the given index * @param stakerNum Index of the staker * @return Address of the staker */ function getStakerAddress(uint256 stakerNum) external view returns (address); /** * @notice Check whether the given staker is staked * @param staker Staker address to check * @return True or False for whether the staker was staked */ function isStaked(address staker) external view returns (bool); /** * @notice Get the latest staked node of the given staker * @param staker Staker address to lookup * @return Latest node staked of the staker */ function latestStakedNode(address staker) external view returns (uint256); /** * @notice Get the current challenge of the given staker * @param staker Staker address to lookup * @return Current challenge of the staker */ function currentChallenge(address staker) external view returns (address); /** * @notice Get the amount staked of the given staker * @param staker Staker address to lookup * @return Amount staked of the staker */ function amountStaked(address staker) external view returns (uint256); /** * @notice Get the original staker address of the zombie at the given index * @param zombieNum Index of the zombie to lookup * @return Original staker address of the zombie */ function zombieAddress(uint256 zombieNum) external view returns (address); /** * @notice Get Latest node that the given zombie at the given index is staked on * @param zombieNum Index of the zombie to lookup * @return Latest node that the given zombie is staked on */ function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint256); /// @return Current number of un-removed zombies function zombieCount() external view returns (uint256); function isZombie(address staker) external view returns (bool); /** * @notice Get the amount of funds withdrawable by the given address * @param owner Address to check the funds of * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view returns (uint256); /** * @return Index of the first unresolved node * @dev If all nodes have been resolved, this will be latestNodeCreated + 1 */ function firstUnresolvedNode() external view returns (uint256); /// @return Index of the latest confirmed node function latestConfirmed() external view returns (uint256); /// @return Index of the latest rollup node created function latestNodeCreated() external view returns (uint256); /// @return Ethereum block that the most recent stake was created function lastStakeBlock() external view returns (uint256); /// @return Number of active stakers currently staked function stakerCount() external view returns (uint256); /// @return Node hash as of this node number function getNodeHash(uint256 index) external view returns (bytes32); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./RollupCore.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/proxy/ProxyAdmin.sol"; import "./RollupEventBridge.sol"; import "./INode.sol"; import "./INodeFactory.sol"; import "../challenge/IChallenge.sol"; import "../challenge/IChallengeFactory.sol"; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/IOutbox.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../bridge/Messages.sol"; import "./RollupLib.sol"; import "../libraries/Cloneable.sol"; import "./facets/IRollupFacets.sol"; abstract contract RollupBase is Cloneable, RollupCore, Pausable { // Rollup Config uint256 public confirmPeriodBlocks; uint256 public extraChallengeTimeBlocks; uint256 public arbGasSpeedLimitPerBlock; uint256 public baseStake; // Bridge is an IInbox and IOutbox IBridge public delayedBridge; ISequencerInbox public sequencerBridge; IOutbox public outbox; RollupEventBridge public rollupEventBridge; IChallengeFactory public challengeFactory; INodeFactory public nodeFactory; address public owner; address public stakeToken; uint256 public minimumAssertionPeriod; uint256 public sequencerInboxMaxDelayBlocks; uint256 public sequencerInboxMaxDelaySeconds; uint256 public challengeExecutionBisectionDegree; address[] internal facets; mapping(address => bool) isValidator; event RollupCreated(bytes32 machineHash); event NodeCreated( uint256 indexed nodeNum, bytes32 indexed parentNodeHash, bytes32 nodeHash, bytes32 executionHash, uint256 inboxMaxCount, uint256 afterInboxBatchEndCount, bytes32 afterInboxBatchAcc, bytes32[3][2] assertionBytes32Fields, uint256[4][2] assertionIntFields ); event NodeConfirmed( uint256 indexed nodeNum, bytes32 afterSendAcc, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount ); event NodeRejected(uint256 indexed nodeNum); event RollupChallengeStarted( address indexed challengeContract, address asserter, address challenger, uint256 challengedNode ); event StakerReassigned(address indexed staker, uint256 newNode); event NodesDestroyed(uint256 indexed startNode, uint256 indexed endNode); event OwnerFunctionCalled(uint256 indexed id); } contract Rollup is RollupBase { // _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, arbGasSpeedLimitPerBlock, baseStake ] // connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory] function initialize( bytes32 _machineHash, uint256[4] calldata _rollupParams, address _stakeToken, address _owner, bytes calldata _extraConfig, address[6] calldata connectedContracts, address[2] calldata _facets, uint256[2] calldata sequencerInboxParams ) public { require(confirmPeriodBlocks == 0, "ALREADY_INIT"); require(_rollupParams[0] != 0, "BAD_CONF_PERIOD"); delayedBridge = IBridge(connectedContracts[0]); sequencerBridge = ISequencerInbox(connectedContracts[1]); outbox = IOutbox(connectedContracts[2]); delayedBridge.setOutbox(connectedContracts[2], true); rollupEventBridge = RollupEventBridge(connectedContracts[3]); delayedBridge.setInbox(connectedContracts[3], true); rollupEventBridge.rollupInitialized( _rollupParams[0], _rollupParams[2], _rollupParams[3], _stakeToken, _owner, _extraConfig ); challengeFactory = IChallengeFactory(connectedContracts[4]); nodeFactory = INodeFactory(connectedContracts[5]); INode node = createInitialNode(_machineHash); initializeCore(node); confirmPeriodBlocks = _rollupParams[0]; extraChallengeTimeBlocks = _rollupParams[1]; arbGasSpeedLimitPerBlock = _rollupParams[2]; baseStake = _rollupParams[3]; owner = _owner; // A little over 15 minutes minimumAssertionPeriod = 75; challengeExecutionBisectionDegree = 400; sequencerInboxMaxDelayBlocks = sequencerInboxParams[0]; sequencerInboxMaxDelaySeconds = sequencerInboxParams[1]; // facets[0] == admin, facets[1] == user facets = _facets; (bool success, ) = _facets[1].delegatecall( abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken) ); require(success, "FAIL_INIT_FACET"); emit RollupCreated(_machineHash); } function createInitialNode(bytes32 _machineHash) private returns (INode) { bytes32 state = RollupLib.stateHash( RollupLib.ExecutionState( 0, // total gas used _machineHash, 0, // inbox count 0, // send count 0, // log count 0, // send acc 0, // log acc block.number, // block proposed 1 // Initialization message already in inbox ) ); return INode( nodeFactory.createNode( state, 0, // challenge hash (not challengeable) 0, // confirm data 0, // prev node block.number // deadline block (not challengeable) ) ); } /** * Fallback and delegate functions from OZ * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/TransparentUpgradeableProxy.sol * And dispatch pattern from EIP-2535: Diamonds */ function getFacets() public view returns (address, address) { return (getAdminFacet(), getUserFacet()); } function getAdminFacet() public view returns (address) { return facets[0]; } function getUserFacet() public view returns (address) { return facets[1]; } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable { _fallback(); } /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { require(msg.data.length >= 4, "NO_FUNC_SIG"); address rollupOwner = owner; // if there is an owner and it is the sender, delegate to admin facet address target = rollupOwner != address(0) && rollupOwner == msg.sender ? getAdminFacet() : getUserFacet(); _delegate(target); } /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./INode.sol"; import "./IRollupCore.sol"; import "./RollupLib.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract RollupCore is IRollupCore { using SafeMath for uint256; struct Zombie { address stakerAddress; uint256 latestStakedNode; } struct Staker { uint256 index; uint256 latestStakedNode; uint256 amountStaked; // currentChallenge is 0 if staker is not in a challenge address currentChallenge; bool isStaked; } uint256 private _latestConfirmed; uint256 private _firstUnresolvedNode; uint256 private _latestNodeCreated; uint256 private _lastStakeBlock; mapping(uint256 => INode) private _nodes; mapping(uint256 => bytes32) private _nodeHashes; address payable[] private _stakerList; mapping(address => Staker) public override _stakerMap; Zombie[] private _zombies; mapping(address => uint256) private _withdrawableFunds; /** * @notice Get the address of the Node contract for the given node * @param nodeNum Index of the node * @return Address of the Node contract */ function getNode(uint256 nodeNum) public view override returns (INode) { return _nodes[nodeNum]; } /** * @notice Get the address of the staker at the given index * @param stakerNum Index of the staker * @return Address of the staker */ function getStakerAddress(uint256 stakerNum) public view override returns (address) { return _stakerList[stakerNum]; } /** * @notice Check whether the given staker is staked * @param staker Staker address to check * @return True or False for whether the staker was staked */ function isStaked(address staker) public view override returns (bool) { return _stakerMap[staker].isStaked; } /** * @notice Get the latest staked node of the given staker * @param staker Staker address to lookup * @return Latest node staked of the staker */ function latestStakedNode(address staker) public view override returns (uint256) { return _stakerMap[staker].latestStakedNode; } /** * @notice Get the current challenge of the given staker * @param staker Staker address to lookup * @return Current challenge of the staker */ function currentChallenge(address staker) public view override returns (address) { return _stakerMap[staker].currentChallenge; } /** * @notice Get the amount staked of the given staker * @param staker Staker address to lookup * @return Amount staked of the staker */ function amountStaked(address staker) public view override returns (uint256) { return _stakerMap[staker].amountStaked; } /** * @notice Get the original staker address of the zombie at the given index * @param zombieNum Index of the zombie to lookup * @return Original staker address of the zombie */ function zombieAddress(uint256 zombieNum) public view override returns (address) { return _zombies[zombieNum].stakerAddress; } /** * @notice Get Latest node that the given zombie at the given index is staked on * @param zombieNum Index of the zombie to lookup * @return Latest node that the given zombie is staked on */ function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) { return _zombies[zombieNum].latestStakedNode; } /// @return Current number of un-removed zombies function zombieCount() public view override returns (uint256) { return _zombies.length; } function isZombie(address staker) public view override returns (bool) { for (uint256 i = 0; i < _zombies.length; i++) { if (staker == _zombies[i].stakerAddress) { return true; } } return false; } /** * @notice Get the amount of funds withdrawable by the given address * @param owner Address to check the funds of * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) public view override returns (uint256) { return _withdrawableFunds[owner]; } /** * @return Index of the first unresolved node * @dev If all nodes have been resolved, this will be latestNodeCreated + 1 */ function firstUnresolvedNode() public view override returns (uint256) { return _firstUnresolvedNode; } /// @return Index of the latest confirmed node function latestConfirmed() public view override returns (uint256) { return _latestConfirmed; } /// @return Index of the latest rollup node created function latestNodeCreated() public view override returns (uint256) { return _latestNodeCreated; } /// @return Ethereum block that the most recent stake was created function lastStakeBlock() public view override returns (uint256) { return _lastStakeBlock; } /// @return Number of active stakers currently staked function stakerCount() public view override returns (uint256) { return _stakerList.length; } /** * @notice Initialize the core with an initial node * @param initialNode Initial node to start the chain with */ function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; } /** * @notice React to a new node being created by storing it an incrementing the latest node counter * @param node Node that was newly created * @param nodeHash The hash of said node */ function nodeCreated(INode node, bytes32 nodeHash) internal { _latestNodeCreated++; _nodes[_latestNodeCreated] = node; _nodeHashes[_latestNodeCreated] = nodeHash; } /// @return Node hash as of this node number function getNodeHash(uint256 index) public view override returns (bytes32) { return _nodeHashes[index]; } function resetNodeHash(uint256 index) internal { _nodeHashes[index] = 0; } /** * @notice Update the latest node created * @param newLatestNodeCreated New value for the latest node created */ function updateLatestNodeCreated(uint256 newLatestNodeCreated) internal { _latestNodeCreated = newLatestNodeCreated; } /// @notice Reject the next unresolved node function rejectNextNode() internal { destroyNode(_firstUnresolvedNode); _firstUnresolvedNode++; } /// @notice Confirm the next unresolved node function confirmNextNode() internal { destroyNode(_latestConfirmed); _latestConfirmed = _firstUnresolvedNode; _firstUnresolvedNode++; } /// @notice Confirm the next unresolved node function confirmLatestNode() internal { destroyNode(_latestConfirmed); uint256 latestNode = _latestNodeCreated; _latestConfirmed = latestNode; _firstUnresolvedNode = latestNode + 1; } /** * @notice Create a new stake * @param stakerAddress Address of the new staker * @param depositAmount Stake amount of the new staker */ function createNewStake(address payable stakerAddress, uint256 depositAmount) internal { uint256 stakerIndex = _stakerList.length; _stakerList.push(stakerAddress); _stakerMap[stakerAddress] = Staker( stakerIndex, _latestConfirmed, depositAmount, address(0), true ); _lastStakeBlock = block.number; } /** * @notice Check to see whether the two stakers are in the same challenge * @param stakerAddress1 Address of the first staker * @param stakerAddress2 Address of the second staker * @return Address of the challenge that the two stakers are in */ function inChallenge(address stakerAddress1, address stakerAddress2) internal view returns (address) { Staker storage staker1 = _stakerMap[stakerAddress1]; Staker storage staker2 = _stakerMap[stakerAddress2]; address challenge = staker1.currentChallenge; require(challenge == staker2.currentChallenge, "IN_CHAL"); require(challenge != address(0), "NO_CHAL"); return challenge; } /** * @notice Make the given staker as not being in a challenge * @param stakerAddress Address of the staker to remove from a challenge */ function clearChallenge(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; staker.currentChallenge = address(0); } /** * @notice Mark both the given stakers as engaged in the challenge * @param staker1 Address of the first staker * @param staker2 Address of the second staker * @param challenge Address of the challenge both stakers are now in */ function challengeStarted( address staker1, address staker2, address challenge ) internal { _stakerMap[staker1].currentChallenge = challenge; _stakerMap[staker2].currentChallenge = challenge; } /** * @notice Add to the stake of the given staker by the given amount * @param stakerAddress Address of the staker to increase the stake of * @param amountAdded Amount of stake to add to the staker */ function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal { Staker storage staker = _stakerMap[stakerAddress]; staker.amountStaked = staker.amountStaked.add(amountAdded); } /** * @notice Reduce the stake of the given staker to the given target * @param stakerAddress Address of the staker to reduce the stake of * @param target Amount of stake to leave with the staker * @return Amount of value released from the stake */ function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) { Staker storage staker = _stakerMap[stakerAddress]; uint256 current = staker.amountStaked; require(target <= current, "TOO_LITTLE_STAKE"); uint256 amountWithdrawn = current.sub(target); staker.amountStaked = target; _withdrawableFunds[stakerAddress] = _withdrawableFunds[stakerAddress].add(amountWithdrawn); return amountWithdrawn; } /** * @notice Remove the given staker and turn them into a zombie * @param stakerAddress Address of the staker to remove */ function turnIntoZombie(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; _zombies.push(Zombie(stakerAddress, staker.latestStakedNode)); deleteStaker(stakerAddress); } /** * @notice Update the latest staked node of the zombie at the given index * @param zombieNum Index of the zombie to move * @param latest New latest node the zombie is staked on */ function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal { _zombies[zombieNum].latestStakedNode = latest; } /** * @notice Remove the zombie at the given index * @param zombieNum Index of the zombie to remove */ function removeZombie(uint256 zombieNum) internal { _zombies[zombieNum] = _zombies[_zombies.length - 1]; _zombies.pop(); } /** * @notice Remove the given staker and return their stake * @param stakerAddress Address of the staker withdrawing their stake */ function withdrawStaker(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; _withdrawableFunds[stakerAddress] = _withdrawableFunds[stakerAddress].add( staker.amountStaked ); deleteStaker(stakerAddress); } /** * @notice Advance the given staker to the given node * @param stakerAddress Address of the staker adding their stake * @param nodeNum Index of the node to stake on */ function stakeOnNode( address stakerAddress, uint256 nodeNum, uint256 confirmPeriodBlocks ) internal { Staker storage staker = _stakerMap[stakerAddress]; INode node = _nodes[nodeNum]; uint256 newStakerCount = node.addStaker(stakerAddress); staker.latestStakedNode = nodeNum; if (newStakerCount == 1) { INode parent = _nodes[node.prev()]; parent.newChildConfirmDeadline(block.number.add(confirmPeriodBlocks)); } } /** * @notice Clear the withdrawable funds for the given address * @param owner Address of the account to remove funds from * @return Amount of funds removed from account */ function withdrawFunds(address owner) internal returns (uint256) { uint256 amount = _withdrawableFunds[owner]; _withdrawableFunds[owner] = 0; return amount; } /** * @notice Increase the withdrawable funds for the given address * @param owner Address of the account to add withdrawable funds to */ function increaseWithdrawableFunds(address owner, uint256 amount) internal { _withdrawableFunds[owner] = _withdrawableFunds[owner].add(amount); } /** * @notice Remove the given staker * @param stakerAddress Address of the staker to remove */ function deleteStaker(address stakerAddress) private { Staker storage staker = _stakerMap[stakerAddress]; uint256 stakerIndex = staker.index; _stakerList[stakerIndex] = _stakerList[_stakerList.length - 1]; _stakerMap[_stakerList[stakerIndex]].index = stakerIndex; _stakerList.pop(); delete _stakerMap[stakerAddress]; } /** * @notice Destroy the given node and clear out its address * @param nodeNum Index of the node to remove */ function destroyNode(uint256 nodeNum) internal { _nodes[nodeNum].destroy(); _nodes[nodeNum] = INode(0); } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./Rollup.sol"; import "./facets/IRollupFacets.sol"; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/IMessageProvider.sol"; import "./INode.sol"; import "../libraries/Cloneable.sol"; contract RollupEventBridge is IMessageProvider, Cloneable { uint8 internal constant INITIALIZATION_MSG_TYPE = 4; uint8 internal constant ROLLUP_PROTOCOL_EVENT_TYPE = 8; uint8 internal constant CREATE_NODE_EVENT = 0; uint8 internal constant CONFIRM_NODE_EVENT = 1; uint8 internal constant REJECT_NODE_EVENT = 2; uint8 internal constant STAKE_CREATED_EVENT = 3; uint8 internal constant CLAIM_NODE_EVENT = 4; IBridge bridge; address rollup; modifier onlyRollup { require(msg.sender == rollup, "ONLY_ROLLUP"); _; } function initialize(address _bridge, address _rollup) external { require(rollup == address(0), "ALREADY_INIT"); bridge = IBridge(_bridge); rollup = _rollup; } function rollupInitialized( uint256 confirmPeriodBlocks, uint256 arbGasSpeedLimitPerBlock, uint256 baseStake, address stakeToken, address owner, bytes calldata extraConfig ) external onlyRollup { bytes memory initMsg = abi.encodePacked( confirmPeriodBlocks, arbGasSpeedLimitPerBlock / 100, // convert avm gas to arbgas uint256(0), baseStake, uint256(uint160(bytes20(stakeToken))), uint256(uint160(bytes20(owner))), extraConfig ); uint256 num = bridge.deliverMessageToInbox(INITIALIZATION_MSG_TYPE, msg.sender, keccak256(initMsg)); emit InboxMessageDelivered(num, initMsg); } function nodeCreated( uint256 nodeNum, uint256 prev, uint256 deadline, address asserter ) external onlyRollup { deliverToBridge( abi.encodePacked( CREATE_NODE_EVENT, nodeNum, prev, block.number, deadline, uint256(uint160(bytes20(asserter))) ) ); } function nodeConfirmed(uint256 nodeNum) external onlyRollup { deliverToBridge(abi.encodePacked(CONFIRM_NODE_EVENT, nodeNum)); } function nodeRejected(uint256 nodeNum) external onlyRollup { deliverToBridge(abi.encodePacked(REJECT_NODE_EVENT, nodeNum)); } function stakeCreated(address staker, uint256 nodeNum) external onlyRollup { deliverToBridge( abi.encodePacked( STAKE_CREATED_EVENT, uint256(uint160(bytes20(staker))), nodeNum, block.number ) ); } function claimNode(uint256 nodeNum, address staker) external onlyRollup { Rollup r = Rollup(payable(rollup)); INode node = r.getNode(nodeNum); require(node.stakers(staker), "NOT_STAKED"); IRollupUser(address(r)).requireUnresolved(nodeNum); deliverToBridge( abi.encodePacked(CLAIM_NODE_EVENT, nodeNum, uint256(uint160(bytes20(staker)))) ); } function deliverToBridge(bytes memory message) private { emit InboxMessageDelivered( bridge.deliverMessageToInbox( ROLLUP_PROTOCOL_EVENT_TYPE, msg.sender, keccak256(message) ), message ); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../challenge/ChallengeLib.sol"; import "./INode.sol"; library RollupLib { struct Config { bytes32 machineHash; uint256 confirmPeriodBlocks; uint256 extraChallengeTimeBlocks; uint256 arbGasSpeedLimitPerBlock; uint256 baseStake; address stakeToken; address owner; address sequencer; uint256 sequencerDelayBlocks; uint256 sequencerDelaySeconds; bytes extraConfig; } struct ExecutionState { uint256 gasUsed; bytes32 machineHash; uint256 inboxCount; uint256 sendCount; uint256 logCount; bytes32 sendAcc; bytes32 logAcc; uint256 proposedBlock; uint256 inboxMaxCount; } function stateHash(ExecutionState memory execState) internal pure returns (bytes32) { return keccak256( abi.encodePacked( execState.gasUsed, execState.machineHash, execState.inboxCount, execState.sendCount, execState.logCount, execState.sendAcc, execState.logAcc, execState.proposedBlock, execState.inboxMaxCount ) ); } struct Assertion { ExecutionState beforeState; ExecutionState afterState; } function decodeExecutionState( bytes32[3] memory bytes32Fields, uint256[4] memory intFields, uint256 proposedBlock, uint256 inboxMaxCount ) internal pure returns (ExecutionState memory) { return ExecutionState( intFields[0], bytes32Fields[0], intFields[1], intFields[2], intFields[3], bytes32Fields[1], bytes32Fields[2], proposedBlock, inboxMaxCount ); } function decodeAssertion( bytes32[3][2] memory bytes32Fields, uint256[4][2] memory intFields, uint256 beforeProposedBlock, uint256 beforeInboxMaxCount, uint256 inboxMaxCount ) internal view returns (Assertion memory) { return Assertion( decodeExecutionState( bytes32Fields[0], intFields[0], beforeProposedBlock, beforeInboxMaxCount ), decodeExecutionState(bytes32Fields[1], intFields[1], block.number, inboxMaxCount) ); } function executionStateChallengeHash(ExecutionState memory state) internal pure returns (bytes32) { return ChallengeLib.assertionHash( state.gasUsed, ChallengeLib.assertionRestHash( state.inboxCount, state.machineHash, state.sendAcc, state.sendCount, state.logAcc, state.logCount ) ); } function executionHash(Assertion memory assertion) internal pure returns (bytes32) { return ChallengeLib.bisectionChunkHash( assertion.beforeState.gasUsed, assertion.afterState.gasUsed - assertion.beforeState.gasUsed, RollupLib.executionStateChallengeHash(assertion.beforeState), RollupLib.executionStateChallengeHash(assertion.afterState) ); } function challengeRoot( Assertion memory assertion, bytes32 assertionExecHash, uint256 blockProposed ) internal pure returns (bytes32) { return challengeRootHash(assertionExecHash, blockProposed, assertion.afterState.inboxCount); } function challengeRootHash( bytes32 execution, uint256 proposedTime, uint256 maxMessageCount ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(execution, proposedTime, maxMessageCount)); } function confirmHash(Assertion memory assertion) internal pure returns (bytes32) { return confirmHash( assertion.beforeState.sendAcc, assertion.afterState.sendAcc, assertion.afterState.logAcc, assertion.afterState.sendCount, assertion.afterState.logCount ); } function confirmHash( bytes32 beforeSendAcc, bytes32 afterSendAcc, bytes32 afterLogAcc, uint256 afterSendCount, uint256 afterLogCount ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( beforeSendAcc, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount ) ); } function feedAccumulator( bytes memory messageData, uint256[] memory messageLengths, bytes32 beforeAcc ) internal pure returns (bytes32) { uint256 offset = 0; uint256 messageCount = messageLengths.length; uint256 dataLength = messageData.length; bytes32 messageAcc = beforeAcc; for (uint256 i = 0; i < messageCount; i++) { uint256 messageLength = messageLengths[i]; require(offset + messageLength <= dataLength, "DATA_OVERRUN"); bytes32 messageHash; assembly { messageHash := keccak256(add(messageData, add(offset, 32)), messageLength) } messageAcc = keccak256(abi.encodePacked(messageAcc, messageHash)); offset += messageLength; } require(offset == dataLength, "DATA_LENGTH"); return messageAcc; } function nodeHash( bool hasSibling, bytes32 lastHash, bytes32 assertionExecHash, bytes32 inboxAcc ) internal pure returns (bytes32) { uint8 hasSiblingInt = hasSibling ? 1 : 0; return keccak256(abi.encodePacked(hasSiblingInt, lastHash, assertionExecHash, inboxAcc)); } function nodeAccumulator(bytes32 prevAcc, bytes32 newNodeHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked(prevAcc, newNodeHash)); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../INode.sol"; import "../../bridge/interfaces/IOutbox.sol"; interface IRollupUser { function initialize(address _stakeToken) external; function completeChallenge(address winningStaker, address losingStaker) external; function returnOldDeposit(address stakerAddress) external; function requireUnresolved(uint256 nodeNum) external view; function requireUnresolvedExists() external view; function countStakedZombies(INode node) external view returns (uint256); } interface IRollupAdmin { /** * @notice Add a contract authorized to put messages into this rollup's inbox * @param _outbox Outbox contract to add */ function setOutbox(IOutbox _outbox) external; /** * @notice Disable an old outbox from interacting with the bridge * @param _outbox Outbox contract to remove */ function removeOldOutbox(address _outbox) external; /** * @notice Enable or disable an inbox contract * @param _inbox Inbox contract to add or remove * @param _enabled New status of inbox */ function setInbox(address _inbox, bool _enabled) external; /** * @notice Pause interaction with the rollup contract */ function pause() external; /** * @notice Resume interaction with the rollup contract */ function resume() external; /** * @notice Set the addresses of rollup logic facets called * @param newAdminFacet address of logic that owner of rollup calls * @param newUserFacet ddress of logic that user of rollup calls */ function setFacets(address newAdminFacet, address newUserFacet) external; /** * @notice Set the addresses of the validator whitelist * @dev It is expected that both arrays are same length, and validator at * position i corresponds to the value at position i * @param _validator addresses to set in the whitelist * @param _val value to set in the whitelist for corresponding address */ function setValidator(address[] memory _validator, bool[] memory _val) external; /** * @notice Set a new owner address for the rollup * @param newOwner address of new rollup owner */ function setOwner(address newOwner) external; /** * @notice Set minimum assertion period for the rollup * @param newPeriod new minimum period for assertions */ function setMinimumAssertionPeriod(uint256 newPeriod) external; /** * @notice Set number of blocks until a node is considered confirmed * @param newConfirmPeriod new number of blocks until a node is confirmed */ function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external; /** * @notice Set number of extra blocks after a challenge * @param newExtraTimeBlocks new number of blocks */ function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external; /** * @notice Set speed limit per block * @param newArbGasSpeedLimitPerBlock maximum arbgas to be used per block */ function setArbGasSpeedLimitPerBlock(uint256 newArbGasSpeedLimitPerBlock) external; /** * @notice Set base stake required for an assertion * @param newBaseStake maximum arbgas to be used per block */ function setBaseStake(uint256 newBaseStake) external; /** * @notice Set the token used for stake, where address(0) == eth * @dev Before changing the base stake token, you might need to change the * implementation of the Rollup User facet! * @param newStakeToken address of token used for staking */ function setStakeToken(address newStakeToken) external; /** * @notice Set max delay in blocks for sequencer inbox * @param newSequencerInboxMaxDelayBlocks max number of blocks */ function setSequencerInboxMaxDelayBlocks(uint256 newSequencerInboxMaxDelayBlocks) external; /** * @notice Set max delay in seconds for sequencer inbox * @param newSequencerInboxMaxDelaySeconds max number of seconds */ function setSequencerInboxMaxDelaySeconds(uint256 newSequencerInboxMaxDelaySeconds) external; /** * @notice Set execution bisection degree * @param newChallengeExecutionBisectionDegree execution bisection degree */ function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree) external; /** * @notice Updates a whitelist address for its consumers * @dev setting the newWhitelist to address(0) disables it for consumers * @param whitelist old whitelist to be deprecated * @param newWhitelist new whitelist to be used * @param targets whitelist consumers to be triggered */ function updateWhitelistConsumers( address whitelist, address newWhitelist, address[] memory targets ) external; /** * @notice Updates a whitelist's entries * @dev user at position i will be assigned value i * @param whitelist whitelist to be updated * @param user users to be updated in the whitelist * @param val if user is or not allowed in the whitelist */ function setWhitelistEntries( address whitelist, address[] memory user, bool[] memory val ) external; /** * @notice Updates a sequencer address at the sequencer inbox * @param newSequencer new sequencer address to be used */ function setSequencer(address newSequencer) external; /** * @notice Upgrades the implementation of a beacon controlled by the rollup * @param beacon address of beacon to be upgraded * @param newImplementation new address of implementation */ function upgradeBeacon(address beacon, address newImplementation) external; }
Get Latest node that the given zombie at the given index is staked on zombieNum Index of the zombie to lookup return Latest node that the given zombie is staked on/
function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) { return _zombies[zombieNum].latestStakedNode; }
200,109
/** *Submitted for verification at Etherscan.io on 2022-04-05 */ // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts/access/[emailΒ protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/access/[emailΒ protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File @openzeppelin/contracts/utils/[emailΒ protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[emailΒ protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[emailΒ protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/utils/introspection/[emailΒ protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/[emailΒ protected] // OpenZeppelin Contracts (last updated v4.5.0) (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 virtual 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 virtual { 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 virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/utils/structs/[emailΒ protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts/access/[emailΒ protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // File @openzeppelin/contracts/token/ERC20/[emailΒ protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/Interfaces/DataInterface.sol pragma solidity 0.8.11; interface DataInterface is IAccessControlEnumerable{ /* solhint-disable */ function ADMIN_ROLE() external pure returns(bytes32); function MODERATOR_ROLE() external pure returns(bytes32); function SALECONTRACT_ROLE() external pure returns(bytes32); /* solhint-enable */ // ******************************************* // ************* MANAGER REGION ************** // ******************************************* function manuallyWhitelistParticipant(address participant_) external; function manuallyBlacklistParticipant(address participant_) external; function manuallyCreditParticipant(address participant_, address tokenInvested_, uint tokenAmount_) external; function setSignersAddress(address signersAddress_) external returns (bool); function setTokenConversion(uint tokenConversion_) external returns (bool); // ***************************************************** // ************* SALECONTRACT_ROLE REGION ************** // ***************************************************** function whitelistParticipant(address participant_, bytes memory signature_) external; function creditParticipation(address participant_, address tokenInvested_, uint tokenAmount_) external; // ************************************************* // ************* DEFAULT_ADMIN REGION ************** // ************************************************* function setRoleAdmin(bytes32 role, bytes32 adminRole) external returns (bool); function salvageTokensFromContract(address tokenAddress, address to, uint amount) external returns (bool); function killContract() external returns (bool); // ******************************************** // ************* INTERNAL REGION ************** // ******************************************** // ************************************************** // ************* PUBLIC GETTERS REGION ************** // ************************************************** function getParticipantCount() external view returns (uint); function getCombinedContributions() external view returns (uint); function getIsParticipantWhitelisted(address participant_) external view returns (bool); function getParticipantContributions(address participant_) external view returns (uint); function getParticipantList(uint startIndex_, uint endIndex_) external view returns (address[] memory, uint[] memory); function getSignersAddress() external view returns (address); function getMessageHash(address contributor_, bool allowed_) external pure returns (bytes32); function getTokenConversion() external view returns (uint); // ****************************************** // ************* EVENTS REGION ************** // ****************************************** event ContributionMade(address indexed contractAddress, address indexed participant_, address tokenInvested_, uint baseAmount_, uint tokensIssued_); event ParticipantWhitelisted(address participant_); event ParticipantBlacklisted(address participant_); event SignersAddressChanged(address oldValue, address newValue); event TokenConversionChanged(uint oldValue, uint newValue); event AdminRoleSet(bytes32 role, bytes32 adminRole); event TokensSalvaged(address tokenAddress, address reciever, uint amount); event ContractKilled(); } // File contracts/DataContract.sol pragma solidity 0.8.11; //import "hardhat/console.sol"; /// @title Authtrail presale data contract /// @author Authtrail llc /// @dev Data contract serves as collection of all the data needed for sucessfull presale /// @custom:experimental This is an experimental contract. contract DataContract is AccessControlEnumerable, DataInterface { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE"); bytes32 public constant SALECONTRACT_ROLE = keccak256("SALECONTRACT_ROLE"); uint private _participantCount; uint private _combinedContributions; address[] private _participantList; mapping(address => bool) private _isParticipantWhitelisted; mapping(address => uint) private _participantContributions; address private _signersAddress; uint private _tokenConversion = 5; constructor(address defaultAdminAddress_, address adminAddress_, address moderatorAddress_, address signersAddress_) { _setupRole(DEFAULT_ADMIN_ROLE, defaultAdminAddress_); _setupRole(ADMIN_ROLE, adminAddress_); _setupRole(MODERATOR_ROLE, moderatorAddress_); _setRoleAdmin(MODERATOR_ROLE, ADMIN_ROLE); _setRoleAdmin(SALECONTRACT_ROLE, ADMIN_ROLE); _setupRole(ADMIN_ROLE, msg.sender); _signersAddress = signersAddress_; } // ******************************************* // ************* MODERATOR REGION ************ // ******************************************* /// @notice Adds participant to whitelist manually /// @dev This method should be used if someone has participated in crowdsale on different conditions /// @param participant_ Participants address function manuallyWhitelistParticipant(address participant_) public onlyRole(MODERATOR_ROLE) override { require(!_isParticipantWhitelisted[participant_], "Participant is already whitelisted!"); _isParticipantWhitelisted[participant_] = true; _participantList.push(participant_); _participantCount += 1; emit ParticipantWhitelisted(participant_); } /// @notice Removes participant from whitelist manually /// @dev This method should be used if participant must be removed from whitelist /// @param participant_ Participants address function manuallyBlacklistParticipant(address participant_) public onlyRole(MODERATOR_ROLE) override { require(_isParticipantWhitelisted[participant_], "Participant is not whitelisted!"); _isParticipantWhitelisted[participant_] = false; emit ParticipantBlacklisted(participant_); } /// @notice Credits participant whithouth him going through presale /// @dev This method should be used if someone has participated in crowdsale on different conditions /// @param participant_ Participants address /// @param tokenAmount_ Amount of tokens participant contributed function manuallyCreditParticipant(address participant_, address tokenInvested_, uint tokenAmount_) public onlyRole(MODERATOR_ROLE) override { require(_isParticipantWhitelisted[participant_], "Participant is not whitelisted!"); _participantContributions[participant_] += tokenAmount_; _combinedContributions += tokenAmount_; emit ContributionMade(msg.sender, participant_, tokenInvested_, tokenAmount_, tokenAmount_ * _tokenConversion); } /// @notice Sets new signer that handles whitelisting on the server /// @dev This method should only be used in ongoing presale if something goes wrong /// @param signersAddress_ New address of the signing account on our backend /// @return default return True after everything is processed function setSignersAddress(address signersAddress_) public onlyRole(MODERATOR_ROLE) override returns (bool) { address oldValue = _signersAddress; require(oldValue != signersAddress_, "Value is already set!"); _signersAddress = signersAddress_; emit SignersAddressChanged(oldValue, signersAddress_); return true; } /// @notice Sets new amount of our tokens that participant will be awarded for 1 stablecoin /// @dev This method should only be used in ongoing presale if something goes wrong /// @param tokenConversion_ New conversion between our token and stable coin contributed /// @return default return True after everything is processed function setTokenConversion(uint tokenConversion_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _tokenConversion; require(oldValue != tokenConversion_, "Value is already set!"); _tokenConversion = tokenConversion_; emit TokenConversionChanged(oldValue, tokenConversion_); return true; } // ***************************************************** // ************* SALECONTRACT_ROLE REGION ************** // ***************************************************** /// @notice Whitelist the participant if signature is done by our signer /// @dev This method is internal method and should be used by presale contract /// @param participant_ Address of the participant /// @param signature_ Signed message of our backend that participant can be whitelisted function whitelistParticipant(address participant_, bytes memory signature_) public onlyRole(SALECONTRACT_ROLE) override { require(!_isParticipantWhitelisted[participant_], "Participant is already whitelisted!"); require(_verify(_signersAddress, participant_, signature_), "Wrong signature!"); _isParticipantWhitelisted[participant_] = true; _participantList.push(participant_); _participantCount += 1; emit ParticipantWhitelisted(participant_); } /// @notice Adds the amount that this participant has contributed /// @dev This method is internal method and should be used by presale contract /// @param participant_ Address of the participant /// @param tokenAmount_ Amount of Stablecoins participant has contributed function creditParticipation(address participant_, address tokenInvested_, uint tokenAmount_) public onlyRole(SALECONTRACT_ROLE) override { _participantContributions[participant_] += tokenAmount_; _combinedContributions += tokenAmount_; emit ContributionMade(msg.sender, participant_, tokenInvested_, tokenAmount_, tokenAmount_ * _tokenConversion); } // ************************************************* // ************* DEFAULT_ADMIN REGION ************** // ************************************************* /// @notice Sets new role admin to the role defined /// @dev This method should only be used if some of priviliged keys are compromised, can only be done by defaultAdmin /// @param role_ Role that we want to change /// @param adminRole_ Role that will become new admin of the changed role /// @return default return True after everything is processed function setRoleAdmin(bytes32 role_, bytes32 adminRole_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool) { _setRoleAdmin(role_, adminRole_); emit AdminRoleSet(role_, adminRole_); return true; } /// @notice Transfer tokens from the contract to desiered address /// @dev This method should be used if users accedentaly sends tokens to our contract address /// @param tokenAddress_ Token address of the token that we want to salvage /// @param to_ Destination where salvaged tokens will be sent /// @param amount_ Amount of tokens we want to salvage /// @return default return True after everything is processed function salvageTokensFromContract(address tokenAddress_, address to_, uint amount_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){ IERC20(tokenAddress_).transfer(to_, amount_); emit TokensSalvaged(tokenAddress_, to_, amount_); return true; } /// @notice Destroys the contract /// @dev This method should NEVER be used if you don't know the implications!!!!!!!! /// @return default return True after everything is processed function killContract() public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){ emit ContractKilled(); selfdestruct(payable(msg.sender)); return true; } // ******************************************** // ************* INTERNAL REGION ************** // ******************************************** function _verify(address signer_, address sender_, bytes memory signature_) internal pure returns(bool) { bytes32 messageHash = getMessageHash(sender_, true); bytes32 ethSignedMessageHash = _getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature_) == signer_; } function _getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) { /* Signature is produced by signing a keccak256 hash with the following format: "\x19Ethereum Signed Message\n" + len(msg) + msg */ return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); } function recoverSigner(bytes32 ethSignedMessageHash_, bytes memory signature_) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(signature_); return ecrecover(ethSignedMessageHash_, v, r, s); } function _splitSignature(bytes memory sig_) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig_.length == 65, "invalid signature length"); assembly { /* First 32 bytes stores the length of the signature add(sig, 32) = pointer of sig + 32 effectively, skips first 32 bytes of signature mload(p) loads next 32 bytes starting at the memory address p into memory */ // first 32 bytes, after the length prefix r := mload(add(sig_, 32)) // second 32 bytes s := mload(add(sig_, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig_, 96))) } // implicitly return (r, s, v) } // ************************************************** // ************* PUBLIC GETTERS REGION ************** // ************************************************** /// @notice Get number of unique participants function getParticipantCount() public view override returns (uint) { return _participantCount; } /// @notice Get all the contributions made function getCombinedContributions() public view override returns (uint) { return _combinedContributions; } /// @notice Get if participants address is whitelisted function getIsParticipantWhitelisted(address participant_) public view override returns (bool) { return _isParticipantWhitelisted[participant_]; } /// @notice Get all contributions for one participant function getParticipantContributions(address participant_) public view override returns (uint) { return _participantContributions[participant_]; } /// @notice Get list of all unique participants and their combined contributions function getParticipantList(uint startIndex_, uint endIndex_) public view override returns (address[] memory, uint[] memory) { uint endIndex = endIndex_; if (endIndex_ > _participantCount) { endIndex = _participantCount; } address[] memory participantAddressArray = new address[](endIndex - startIndex_); uint[] memory participantContributionArray = new uint[](endIndex - startIndex_); for (uint i=0; i<endIndex - startIndex_; i++) { participantAddressArray[i] = _participantList[i + startIndex_]; participantContributionArray[i] = getParticipantContributions(participantAddressArray[i]); } return (participantAddressArray, participantContributionArray); } /// @notice Get public key of our backend signer function getSignersAddress() public view override returns (address) { return _signersAddress; } /// @notice Keccak message to use for proof function getMessageHash(address contributor_, bool allowed_) public pure override returns (bytes32) { return keccak256(abi.encodePacked(contributor_, allowed_)); } /// @notice Amount of our tokens user will get for 1 stablecoin contributed function getTokenConversion() public view override returns (uint) { return _tokenConversion; } }
Transfer tokens from the contract to desiered address This method should be used if users accedentaly sends tokens to our contract address tokenAddress_ Token address of the token that we want to salvage to_ Destination where salvaged tokens will be sent amount_ Amount of tokens we want to salvage return default return True after everything is processed
function salvageTokensFromContract(address tokenAddress_, address to_, uint amount_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){ IERC20(tokenAddress_).transfer(to_, amount_); emit TokensSalvaged(tokenAddress_, to_, amount_); return true; }
8,004,935
pragma solidity 0.4.25; import "./SafeMath.sol"; import "./Roles.sol"; /** * @title TRC20 interface */ interface TRC20Interface { function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title Standard TRC20 token * @dev Implementation of the basic standard token. */ contract TRC20 is TRC20Interface { using SafeMath for uint256; uint256 public totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; function() public payable { revert(); } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public view returns (uint256) { return balances[tokenOwner]; } /** * @dev Function to check the amount of tokens that an tokenOwner allowed to a * spender. * @param tokenOwner 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 tokenOwner, address spender) public view returns (uint256) { return allowed[tokenOwner][spender]; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param tokens The amount to be transferred. */ function transfer(address to, uint256 tokens) public returns (bool) { require(to != address(0)); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); 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: * @param spender The address which will spend the funds. * @param tokens The amount of tokens to be spent. */ function approve(address spender, uint256 tokens) public returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); 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 tokens uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 tokens) public returns (bool) { require(to != address(0)); require(tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } }
Function to check the amount of tokens that an tokenOwner allowed to a spender. tokenOwner address The address which owns the funds. 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 tokenOwner, address spender) public view returns (uint256) { return allowed[tokenOwner][spender]; }
12,758,010
/// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.7; pragma abicoder v2; //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘// // @function getBytes // function getBytes( uint256 gasLimit, uint256 sizeLimit, address addr, bytes memory data ) view returns (uint256 status, bytes memory result) { assembly { // @param Allocate a new slot for the output // result := mload(0x40) // @note Initialize the output as length 0 (in case things go wrong) // mstore(result, 0) mstore(0x40, add(result, 32)) // @dev Call the target address with the data, limiting gas usage // status := staticcall(gasLimit, addr, add(data, 32), mload(data), 0, 0) // @return returns or revert is a reasonable length // if lt(returndatasize(), sizeLimit) { // @dev Allocate enough space to store the ceil_32(len_32(result) + result) // mstore( 0x40, add( result, and(add(add(returndatasize(), 0x20), 0x1f), not(0x1f)) ) ) // @note Place the length of the result value into the output // mstore(result, returndatasize()) // @note Copy the result value into the output // returndatacopy(add(result, 32), 0, returndatasize()) } } } //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘// contract SushiCall { struct Call { address target; uint256 gasLimit; bytes callData; } struct Result { bool success; uint256 gasUsed; bytes returnData; } struct Output { bool success; bytes data; } //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘// // @function getCurrentBlockTimestamp // function getCurrentBlockTimestamp() public view returns (uint256 timestamp) { timestamp = block.timestamp; } // @function getEthBalance // function getEthBalance(address addr) public view returns (uint256 balance) { balance = addr.balance; } function sushicall(Call[] memory calls) public returns (uint256 blockNumber, Result[] memory returnData) { blockNumber = block.number; returnData = new Result[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (address target, uint256 gasLimit, bytes memory callData) = ( calls[i].target, calls[i].gasLimit, calls[i].callData ); uint256 gasLeftBefore = gasleft(); (bool success, bytes memory ret) = target.call{ gas: gasLimit }( callData ); uint256 gasUsed = gasLeftBefore - gasleft(); returnData[i] = Result(success, gasUsed, ret); } } //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘// // @note this is confusing with `gasLimit` on line 78 function gaslimit() external view returns (uint256) { return block.gaslimit; } function gasLeft() external view returns (uint256) { return gasleft(); } function gasBase() public view returns (uint256 ret) { assembly { ret := basefee() } } /** * @notice Get the Ether balance for all addresses specified * @param addresses The addresses to get the Ether balance for * @return results The Ether balance for all addresses in the same order as specified */ function etherBalances(address[] calldata addresses) external view returns (Output[] memory results) { results = new Output[](addresses.length); for (uint256 i = 0; i < addresses.length; i++) { results[i] = Output(true, abi.encode(addresses[i].balance)); } } /** * @notice Get the ERC-20 token balance of `token` for all addresses specified * @dev This does not check if the `token` address specified is actually an ERC-20 token * @param addresses The addresses to get the token balance for * @param token The address of the ERC-20 token contract * @return results The token balance for all addresses in the same order as specified */ function tokenBalances(address[] calldata addresses, address token) external view returns (Output[] memory results) { results = new Output[](addresses.length); for (uint256 i = 0; i < addresses.length; i++) { bytes memory data = abi.encodeWithSignature("balanceOf(address)", addresses[i]); results[i] = staticCall(token, data, 20000); } } /** * @notice Get the ERC-20 token balance from multiple contracts for a single owner * @param owner The address of the token owner * @param contracts The addresses of the ERC-20 token contracts * @return results The token balances in the same order as the addresses specified */ function tokensBalance(address owner, address[] calldata contracts) external view returns (Output[] memory results) { results = new Output[](contracts.length); bytes memory data = abi.encodeWithSignature("balanceOf(address)", owner); for (uint256 i = 0; i < contracts.length; i++) { results[i] = staticCall(contracts[i], data, 20000); } } /** * @notice Call multiple contracts with the provided arbitrary data * @param contracts The contracts to call * @param data The data to call the contracts with * @return results The raw result of the contract calls */ function call(address[] calldata contracts, bytes[] calldata data) external view returns (Output[] memory results) { return call(contracts, data, gasleft()); } /** * @notice Call multiple contracts with the provided arbitrary data * @param contracts The contracts to call * @param data The data to call the contracts with * @param gas The amount of gas to call the contracts with * @return results The raw result of the contract calls */ function call( address[] calldata contracts, bytes[] calldata data, uint256 gas ) public view returns (Output[] memory results) { require(contracts.length == data.length, "Length must be equal"); results = new Output[](contracts.length); for (uint256 i = 0; i < contracts.length; i++) { results[i] = staticCall(contracts[i], data[i], gas); } } /** * @notice Static call a contract with the provided data * @param target The address of the contract to call * @param data The data to call the contract with * @param gas The amount of gas to forward to the call * @return result The result of the contract call */ function staticCall( address target, bytes memory data, uint256 gas ) private view returns (Output memory) { uint256 size = codeSize(target); if (size > 0) { (bool success, bytes memory result) = target.staticcall{ gas: gas }(data); if (success) { return Output(success, result); } } return Output(false, ""); } /** * @notice Get code size of address * @param _address The address to get code size from * @return size Unsigned 256-bits integer */ function codeSize(address _address) private view returns (uint256 size) { // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_address) } } }
Static call a contract with the provided data target The address of the contract to call data The data to call the contract with gas The amount of gas to forward to the call return result The result of the contract call/
function staticCall( address target, bytes memory data, uint256 gas ) private view returns (Output memory) { uint256 size = codeSize(target); if (size > 0) { if (success) { return Output(success, result); } } return Output(false, ""); }
12,973,575