file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// File: @openzeppelin/contracts@4.4.1/utils/Create2.sol // OpenZeppelin Contracts v4.4.1 (utils/Create2.sol) pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy( uint256 amount, bytes32 salt, bytes memory bytecode ) internal returns (address) { address addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress( bytes32 salt, bytes32 bytecodeHash, address deployer ) internal pure returns (address) { bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)); return address(uint160(uint256(_data))); } } // File: @openzeppelin/contracts@4.4.1/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts@4.4.1/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: recycle.sol pragma solidity ^0.8.0; contract RecycleFactory is ReentrancyGuard { function recycle(address payable to,uint[] calldata uids, address[] calldata erc20) nonReentrant external { uint n=uids.length; for (uint i=0; i < n; i++) { uint uid=uids[i]; address recycleContract = computeAddress(msg.sender,uid); if(!Address.isContract(recycleContract)){ bytes32 salt = keccak256(abi.encode(msg.sender, uid)); bytes memory bytecode = type(Recycle).creationCode; recycleContract=Create2.deploy(0,salt,bytecode); Recycle(recycleContract).init(address(this)); } Recycle(recycleContract).recycle(to,erc20); } } function computeAddress(address sender,uint uid) public view returns(address) { bytes32 salt = keccak256(abi.encode(sender, uid)); bytes32 bytecodeHash = keccak256(type(Recycle).creationCode); return Create2.computeAddress(salt,bytecodeHash); } } contract Recycle is ReentrancyGuard { address public factory; function init(address _factory) external { require(factory==address(0),"Recycle: cannot init"); factory=_factory; } function recycle(address payable recycler, address[] calldata erc20) external nonReentrant { require(msg.sender==factory,"Recycle: must factory"); uint n=erc20.length; for (uint i; i < n; i++) { RecyleHelper.transfer(erc20[i],recycler); } uint balance=address(this).balance; if(balance>0) { recycler.transfer(balance); } } } library RecyleHelper { function transfer(address token, address to) internal returns (bool) { uint value = balanceOf(token); if (value > 0){ (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); return success && (data.length == 0 || abi.decode(data, (bool))); } return true; } function balanceOf(address token) internal returns (uint) { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x70a08231, address(this))); if (!success || data.length == 0) return 0; return abi.decode(data, (uint)); } }
Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecodeHash` or `salt` will result in a new destination address./
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); }
1,682
./full_match/80001/0x50b4cB2C152322760a8fA59105A46745CE2B7Eac/sources/src/Facets/GetGasFacet.sol
Performs a swap before bridging via GetGas Bridge _bridgeData Data used purely for tracking and analytics _swapData An array of swap related data for performing swaps before bridging
function swapAndStartBridgeTokensViaGetGas( ILiFi.BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) containsSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender) ); _startBridge(_bridgeData); }
9,508,193
pragma solidity ^0.4.18; library Bytes { function concat(bytes memory self, bytes memory bts) internal view returns (bytes memory newBts) { uint totLen = self.length + bts.length; if (totLen == 0) return; newBts = new bytes(totLen); assembly { let i := 0 let inOffset := 0 let outOffset := add(newBts, 0x20) let words := 0 let tag := tag_bts tag_self: inOffset := add(self, 0x20) words := div(add(mload(self), 31), 32) jump(tag_loop) tag_bts: i := 0 inOffset := add(bts, 0x20) outOffset := add(newBts, add(0x20, mload(self))) words := div(add(mload(bts), 31), 32) tag := tag_end tag_loop: jumpi(tag, gt(i, words)) { let offset := mul(i, 32) outOffset := add(outOffset, offset) mstore(outOffset, mload(add(inOffset, offset))) i := add(i, 1) } jump(tag_loop) tag_end: mstore(add(newBts, add(totLen, 0x20)), 0) } } function uintToBytes(uint self) internal pure returns (bytes memory s) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (self != 0) { uint remainder = self % 10; self = self / 10; reversed[i++] = byte(48 + remainder); } s = new bytes(i); for (uint j = 0; j < i; j++) { s[j] = reversed[i - 1 - j]; } return s; } } contract PlasmaChild { // library using Bytes for *; // deposit uint256 public lastEthBlockNumber = block.number; uint256 public depositCounterInBlock = 0; mapping (uint256 => DepositRecord) public depositRecords; mapping (address => uint256[]) userDepositRecords; enum DepositStatus { NoRecord, Deposited, WithdrawStarted, WithdrawChallenged, WithdrawCompleted, DepositConfirmed } struct DepositRecord { address from; DepositStatus status; uint256 amount; uint256 index; uint256 withdrawStartedTime; } // when someone deposit event DepositEvent(address indexed _from, uint256 indexed _amount, uint256 indexed _depositIndex); // function deposit(uint256 _amount) public returns (uint256 idx1, uint256 idx2, uint256 idx3) public onlyToken { /* function deposit(address _address, uint256 _amount) public returns (uint256 idx1, uint256 idx2, uint256 idx3) { */ function deposit(address _address, uint256 _amount) public returns (uint256 idx) { // lastEthBlockNumber is not updatede at all... // depositCounterInBlock may not be used yet... if (block.number != lastEthBlockNumber) { depositCounterInBlock = 0; } // seems to generate unique depositIndex uint256 depositIndex = block.number << 32 + depositCounterInBlock; // then create new DepositRecord object DepositRecord storage record = depositRecords[depositIndex]; require(record.index == 0); require(record.status == DepositStatus.NoRecord); record.index = depositIndex; record.from = _address; record.amount = _amount; record.status = DepositStatus.Deposited; depositCounterInBlock = depositCounterInBlock + 1; userDepositRecords[_address].push(depositIndex); /* DepositEvent(msg.sender, msg.value, depositIndex); */ DepositEvent(_address, _amount, depositIndex); return (depositIndex); } // update deposit record function updateDepositRecord(uint256 _depositIndex, uint8 _status) public onlyOwner returns (bool success) { DepositRecord storage record = depositRecords[_depositIndex]; if (record.status == DepositStatus.NoRecord) revert(); if (_status == 5) { record.status = DepositStatus.DepositConfirmed; } return true; } // helper function for debug function depositRecordsForUser(address _user) public view returns (uint256[]) { return userDepositRecords[_user]; } // new block number (lastEventProcessedBlockPrefix) uint32 lastEventProcessedBlockNumber; // last block number; uint32 lastPlasmaBlockNumber; // last block hash bytes32 lastPlasmaBlockHash; // current block number uint32 public currentPlasmaBlockNumber = 1; // structs // header struct PlasmaBlockHeader { uint32 blockNumber; uint32 numTransactions; bytes32 previousBlockHash; bytes32 merkleRootHash; uint8 v; bytes32 r; bytes32 s; } mapping (uint32 => PlasmaBlockHeader) public plasmaBlockHeaders; // Owner Address address public ownerAddress; // Modifiers modifier onlyOwner { if (msg.sender != ownerAddress) revert(); _; } // Constructor function PlasmaChild() public { ownerAddress = msg.sender; } // update plasma header once block is created function updatePlasmaBlockHeader( uint32 _bn, uint32 _txCount, bytes32 _parentHash, bytes32 _merkleRootHash, uint8 _v, bytes32 _r, bytes32 _s ) onlyOwner public returns (bool success) { PlasmaBlockHeader ph = plasmaBlockHeaders[_bn]; ph.blockNumber = _bn; ph.previousBlockHash = _parentHash; ph.merkleRootHash = _merkleRootHash; ph.v = _v; ph.r = _r; ph.s = _s; return true; } // convenient function for debugging function updateNumTransactions(uint32 _bn, uint32 _txCount) onlyOwner public returns(bool success) { PlasmaBlockHeader ph = plasmaBlockHeaders[_bn]; ph.numTransactions = _txCount; return true; } // create next block function createNextBlock() onlyOwner public returns (bool success) { currentPlasmaBlockNumber = currentPlasmaBlockNumber + 1; PlasmaBlockHeader ph = plasmaBlockHeaders[currentPlasmaBlockNumber]; ph.blockNumber = currentPlasmaBlockNumber; return true; } // get block number and transactions of last block function getLastBlockNumberandTXcount() public view returns (uint32 _bn, uint32 _numTxs ) { if ( currentPlasmaBlockNumber == 0) revert(); uint32 lastPlasmaBlockNumber = currentPlasmaBlockNumber - 1; PlasmaBlockHeader ph = plasmaBlockHeaders[lastPlasmaBlockNumber]; return ( lastPlasmaBlockNumber, ph.numTransactions); } // get block number and transactions of current block function getCurrentBlockNumberandTXcount() public view returns (uint32 _bn, uint32 _numTxs ) { // block number start from 1 if ( currentPlasmaBlockNumber == 0) revert(); /* uint32 lastPlasmaBlockNumber = currentPlasmaBlockNumber - 1; */ PlasmaBlockHeader ph = plasmaBlockHeaders[currentPlasmaBlockNumber]; return ( currentPlasmaBlockNumber, ph.numTransactions); } // plasma event event PlasmaTransactionEvent(uint32 txIdx, uint32 currentPlasmaBlockNumber, bytes txData); // array of plasma transactions mapping (uint32 => bytes[]) public plasmaTransactions; // add transactin function submitPlasmaTransaction(bytes txData) onlyOwner public returns (bool success) { // get plasma block header with current plasma block number PlasmaBlockHeader ph = plasmaBlockHeaders[currentPlasmaBlockNumber]; // increase number of transactions uint32 lastNumTransactions = ph.numTransactions; ph.numTransactions = ph.numTransactions + 1; // add transaction plasmaTransactions[currentPlasmaBlockNumber].push(txData); // send event PlasmaTransactionEvent(lastNumTransactions, currentPlasmaBlockNumber, txData); return true; } // change ownerheaders function transferOwner(address _address) public onlyOwner { ownerAddress = _address; } // kill contract itself function kill() onlyOwner public { selfdestruct(ownerAddress); } function setCurrentPlasmaBlockNumber(uint32 _number) onlyOwner public returns (bool success) { currentPlasmaBlockNumber = _number; return true; } // fallback for ether function() payable public { revert(); } }
get block number and transactions of current block block number start from 1
function getCurrentBlockNumberandTXcount() public view returns (uint32 _bn, uint32 _numTxs ) { if ( currentPlasmaBlockNumber == 0) revert(); PlasmaBlockHeader ph = plasmaBlockHeaders[currentPlasmaBlockNumber]; return ( currentPlasmaBlockNumber, ph.numTransactions);
925,323
./partial_match/137/0x309523B3B73A68079fB9D9A8da08c642dF8d1b93/sources/project_/contracts/GenesisMinter.sol
Interfaces to access minter and details editor functions User has not reached the limit yet Setup avatar attributes
function teamMint() external onlyRole(TEAM_MINTER_ROLE) { AvatarDetailEditor detailEditor = AvatarDetailEditor( genesisAvatarContract ); SimpleAvatarMinter genesisAvatarInstance = SimpleAvatarMinter( genesisAvatarContract ); for (uint256 i = 0; i < 10; i++) { uint256 currentTokenId = detailEditor.getCurrentTokenId(); genesisAvatarInstance.mintAvatarSimple(msg.sender); detailEditor.updateRoyalties( currentTokenId, INITIAL_GENESIS_ROYALTIES ); detailEditor.updateTribe(currentTokenId, "Dwarf"); } }
3,512,601
./full_match/4/0x164c24d0844c267DA15a4c841eaBae817d211EA1/sources/Users/hristiyangeorgiev/Documents/Projects/Redemeum/ERC20/bsn-core-prototype/contracts/ERC1155ERC721.sol
Check successful transfer if recipient is a contract ERC-1155 _operator The operator of the transfer _from Address of sender _to Address of recipient _tokenId ID of the token _value Value transferred _data Optional data/
function _doSafeTransferAcceptanceCheck( address _operator, address _from, address _to, uint256 _tokenId, uint256 _value, bytes memory _data ) internal { if(_to.isContract()) { require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _tokenId, _value, _data) == } }
13,350,719
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./base/Controller.sol"; import "./base/EternalStorage.sol"; import "./base/IEntityFundingFacet.sol"; import "./base/IDiamondFacet.sol"; import "./base/IERC20.sol"; import "./base/IMarket.sol"; import "./base/SafeMath.sol"; import "./EntityFacetBase.sol"; contract EntityFundingFacet is EternalStorage, Controller, EntityFacetBase, IEntityFundingFacet, IDiamondFacet { using SafeMath for uint256; modifier assertCanTradeTrancheTokens () { require(inRoleGroup(msg.sender, ROLEGROUP_TRADERS), 'must be trader'); _; } /** * Constructor */ constructor (address _settings) Controller(_settings) public { } // IDiamondFacet function getSelectors () public pure override returns (bytes memory) { return abi.encodePacked( IEntityFundingFacet.getBalance.selector, IEntityFundingFacet.deposit.selector, IEntityFundingFacet.withdraw.selector, IEntityFundingFacet.trade.selector, IEntityFundingFacet.sellAtBestPrice.selector ); } // IEntityFundingFacet function getBalance(address _unit) public view override returns (uint256) { return dataUint256[__a(_unit, "balance")]; } function deposit(address _unit, uint256 _amount) external override { IERC20 tok = IERC20(_unit); tok.transferFrom(msg.sender, address(this), _amount); dataUint256[__a(_unit, "balance")] = dataUint256[__a(_unit, "balance")].add(_amount); emit EntityDeposit(msg.sender, _unit, _amount); } function withdraw(address _unit, uint256 _amount) external override assertIsEntityAdmin(msg.sender) { require(dataUint256["tokenSupply"] == 0, "cannot withdraw while tokens exist"); _assertHasEnoughBalance(_unit, _amount); dataUint256[__a(_unit, "balance")] = dataUint256[__a(_unit, "balance")].sub(_amount); IERC20 tok = IERC20(_unit); tok.transfer(msg.sender, _amount); emit EntityWithdraw(msg.sender, _unit, _amount); } function trade(address _payUnit, uint256 _payAmount, address _buyUnit, uint256 _buyAmount) external override assertCanTradeTrancheTokens returns (uint256) { // check balance _assertHasEnoughBalance(_payUnit, _payAmount); // do it return _tradeOnMarket(_payUnit, _payAmount, _buyUnit, _buyAmount, FEE_SCHEDULE_STANDARD, address(0), ""); } function sellAtBestPrice(address _sellUnit, uint256 _sellAmount, address _buyUnit) external override assertCanTradeTrancheTokens { // check balance _assertHasEnoughBalance(_sellUnit, _sellAmount); // do it! _sellAtBestPriceOnMarket(_sellUnit, _sellAmount, _buyUnit); } }
check balance do it
function trade(address _payUnit, uint256 _payAmount, address _buyUnit, uint256 _buyAmount) external override assertCanTradeTrancheTokens returns (uint256) { _assertHasEnoughBalance(_payUnit, _payAmount); return _tradeOnMarket(_payUnit, _payAmount, _buyUnit, _buyAmount, FEE_SCHEDULE_STANDARD, address(0), ""); }
12,675,792
// SPDX-License-Identifier: MIT /** ∩~~~~∩ ξ ・×・ ξ ξ ~ ξ ξ   ξ ξ   “~~~~〇 ξ       ξ ξ ξ ξ~~~ξ ξ ξ   ξ_ξξ_ξ ξ_ξξ_ξ Alpaca Fin Corporation **/ pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IBEP20.sol"; import "./interfaces/IFairLaunch.sol"; import "./interfaces/IGrassHouse.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IProxyToken.sol"; import "./SafeToken.sol"; /// @title AlpacaFeeder contract AlpacaFeeder is IVault, Initializable, OwnableUpgradeable { /// @notice Libraries using SafeToken for address; /// @notice Events event LogFeedGrassHouse(uint256 _feedAmount); event LogFairLaunchDeposit(); event LogFairLaunchWithdraw(); event LogFairLaunchHarvest(address _caller, uint256 _harvestAmount); event LogSetNewGrassHouse(address indexed _caller, address _prevGrassHouse, address _newGrassHouse); /// @notice State IFairLaunch public fairLaunch; IGrassHouse public grassHouse; uint256 public fairLaunchPoolId; /// @notice Attributes for AlcapaFeeder /// token - address of the token to be deposited in this contract /// proxyToken - just a simple ERC20 token for staking with FairLaunch address public override token; address public proxyToken; function initialize( address _token, address _proxyToken, address _fairLaunchAddress, uint256 _fairLaunchPoolId, address _grasshouseAddress ) external initializer { OwnableUpgradeable.__Ownable_init(); token = _token; proxyToken = _proxyToken; fairLaunchPoolId = _fairLaunchPoolId; fairLaunch = IFairLaunch(_fairLaunchAddress); grassHouse = IGrassHouse(_grasshouseAddress); (address _stakeToken, , , , ) = fairLaunch.poolInfo(fairLaunchPoolId); require(_stakeToken == _proxyToken, "!same stakeToken"); require(grassHouse.rewardToken() == _token, "!same rewardToken"); proxyToken.safeApprove(_fairLaunchAddress, type(uint256).max); } /// @notice Deposit token to FairLaunch function fairLaunchDeposit() external onlyOwner { require(IBEP20(proxyToken).balanceOf(address(fairLaunch)) == 0, "already deposit"); IProxyToken(proxyToken).mint(address(this), 1e18); fairLaunch.deposit(address(this), fairLaunchPoolId, 1e18); emit LogFairLaunchDeposit(); } /// @notice Withdraw all staked token from FairLaunch function fairLaunchWithdraw() external onlyOwner { fairLaunch.withdrawAll(address(this), fairLaunchPoolId); IProxyToken(proxyToken).burn(address(this), proxyToken.myBalance()); emit LogFairLaunchWithdraw(); } /// @notice Receive reward from FairLaunch function fairLaunchHarvest() external { _fairLaunchHarvest(); } /// @notice Receive reward from FairLaunch function _fairLaunchHarvest() internal { uint256 _before = token.myBalance(); (bool _success, ) = address(fairLaunch).call(abi.encodeWithSelector(0xddc63262, fairLaunchPoolId)); if (_success) emit LogFairLaunchHarvest(address(this), token.myBalance() - _before); } /// @notice Harvest reward from FairLaunch and Feed token to a GrassHouse function feedGrassHouse() external { _fairLaunchHarvest(); uint256 _feedAmount = token.myBalance(); token.safeApprove(address(grassHouse), _feedAmount); grassHouse.feed(_feedAmount); emit LogFeedGrassHouse(_feedAmount); } /// @notice Set a new GrassHouse /// @param _newGrassHouse - new GrassHouse address function setGrassHouse(IGrassHouse _newGrassHouse) external onlyOwner { address _prevGrassHouse = address(grassHouse); grassHouse = _newGrassHouse; emit LogSetNewGrassHouse(msg.sender, _prevGrassHouse, address(_newGrassHouse)); } }
Receive reward from FairLaunch
function _fairLaunchHarvest() internal { uint256 _before = token.myBalance(); (bool _success, ) = address(fairLaunch).call(abi.encodeWithSelector(0xddc63262, fairLaunchPoolId)); if (_success) emit LogFairLaunchHarvest(address(this), token.myBalance() - _before); }
12,869,468
// SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Registry} from "../registry/Registry.sol"; import {OwnedUpgradeabilityProxy} from "../proxy/OwnedUpgradeabilityProxy.sol"; import {TrueCurrencyWithGasRefund} from "./TrueCurrencyWithGasRefund.sol"; /** * @dev Contract that can be called with a gas refund */ interface IHook { function hook() external; } interface IHasOwner { function claimOwnership() external; function transferOwnership(address newOwner) external; } /** @title TokenController * @dev This contract allows us to split ownership of the TrueCurrency contract * into two addresses. One, called the "owner" address, has unfettered control of the TrueCurrency contract - * it can mint new tokens, transfer ownership of the contract, etc. However to make * extra sure that TrueCurrency is never compromised, this owner key will not be used in * day-to-day operations, allowing it to be stored at a heightened level of security. * Instead, the owner appoints an various "admin" address. * There are 3 different types of admin addresses; MintKey, MintRatifier, and MintPauser. * MintKey can request and revoke mints one at a time. * MintPausers can pause individual mints or pause all mints. * MintRatifiers can approve and finalize mints with enough approval. * There are three levels of mints: instant mint, ratified mint, and multiSig mint. Each have a different threshold * and deduct from a different pool. * Instant mint has the lowest threshold and finalizes instantly without any ratifiers. Deduct from instant mint pool, * which can be refilled by one ratifier. * Ratify mint has the second lowest threshold and finalizes with one ratifier approval. Deduct from ratify mint pool, * which can be refilled by three ratifiers. * MultiSig mint has the highest threshold and finalizes with three ratifier approvals. Deduct from multiSig mint pool, * which can only be refilled by the owner. */ contract TokenController { using SafeMath for uint256; struct MintOperation { address to; uint256 value; uint256 requestedBlock; uint256 numberOfApproval; bool paused; mapping(address => bool) approved; } address payable public owner; address payable public pendingOwner; bool public initialized; uint256 public instantMintThreshold; uint256 public ratifiedMintThreshold; uint256 public multiSigMintThreshold; uint256 public instantMintLimit; uint256 public ratifiedMintLimit; uint256 public multiSigMintLimit; uint256 public instantMintPool; uint256 public ratifiedMintPool; uint256 public multiSigMintPool; address[2] public ratifiedPoolRefillApprovals; uint8 public constant RATIFY_MINT_SIGS = 1; //number of approvals needed to finalize a Ratified Mint uint8 public constant MULTISIG_MINT_SIGS = 3; //number of approvals needed to finalize a MultiSig Mint bool public mintPaused; uint256 public mintReqInvalidBeforeThisBlock; //all mint request before this block are invalid address public mintKey; MintOperation[] public mintOperations; //list of a mint requests TrueCurrencyWithGasRefund public token; Registry public registry; address public registryAdmin; address public gasRefunder; // Registry attributes for admin keys bytes32 public constant IS_MINT_PAUSER = "isTUSDMintPausers"; bytes32 public constant IS_MINT_RATIFIER = "isTUSDMintRatifier"; bytes32 public constant IS_REDEMPTION_ADMIN = "isTUSDRedemptionAdmin"; // paused version of TrueCurrency in Production // pausing the contract upgrades the proxy to this implementation address public constant PAUSED_IMPLEMENTATION = 0x3c8984DCE8f68FCDEEEafD9E0eca3598562eD291; modifier onlyMintKeyOrOwner() { require(msg.sender == mintKey || msg.sender == owner, "must be mintKey or owner"); _; } modifier onlyMintPauserOrOwner() { require(registry.hasAttribute(msg.sender, IS_MINT_PAUSER) || msg.sender == owner, "must be pauser or owner"); _; } modifier onlyMintRatifierOrOwner() { require(registry.hasAttribute(msg.sender, IS_MINT_RATIFIER) || msg.sender == owner, "must be ratifier or owner"); _; } modifier onlyOwnerOrRedemptionAdmin() { require(registry.hasAttribute(msg.sender, IS_REDEMPTION_ADMIN) || msg.sender == owner, "must be Redemption admin or owner"); _; } modifier onlyGasRefunder() { require(msg.sender == gasRefunder || msg.sender == owner, "must be gas refunder or owner"); _; } modifier onlyRegistryAdmin() { require(msg.sender == registryAdmin || msg.sender == owner, "must be registry admin or owner"); _; } //mint operations by the mintkey cannot be processed on when mints are paused modifier mintNotPaused() { if (msg.sender != owner) { require(!mintPaused, "minting is paused"); } _; } /// @dev Emitted when ownership of controller was transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev Emitted when ownership of controller transfer procedure was started event NewOwnerPending(address indexed currentOwner, address indexed pendingOwner); /// @dev Emitted when new registry was set event SetRegistry(address indexed registry); /// @dev Emitted when owner was transferred for child contract event TransferChild(address indexed child, address indexed newOwner); /// @dev Emitted when child ownership was claimed event RequestReclaimContract(address indexed other); /// @dev Emitted when child token was changed event SetToken(TrueCurrencyWithGasRefund newContract); /// @dev Emitted when canBurn status of the `burner` was changed to `canBurn` event CanBurn(address burner, bool canBurn); /// @dev Emitted when mint was requested event RequestMint(address indexed to, uint256 indexed value, uint256 opIndex, address mintKey); /// @dev Emitted when mint was finalized event FinalizeMint(address indexed to, uint256 indexed value, uint256 opIndex, address mintKey); /// @dev Emitted on instant mint event InstantMint(address indexed to, uint256 indexed value, address indexed mintKey); /// @dev Emitted when mint key was replaced event TransferMintKey(address indexed previousMintKey, address indexed newMintKey); /// @dev Emitted when mint was ratified event MintRatified(uint256 indexed opIndex, address indexed ratifier); /// @dev Emitted when mint is revoked event RevokeMint(uint256 opIndex); /// @dev Emitted when all mining is paused (status=true) or unpaused (status=false) event AllMintsPaused(bool status); /// @dev Emitted when opIndex mint is paused (status=true) or unpaused (status=false) event MintPaused(uint256 opIndex, bool status); /// @dev Emitted when mint is approved event MintApproved(address approver, uint256 opIndex); /// @dev Emitted when fast pause contract is changed event FastPauseSet(address _newFastPause); /// @dev Emitted when mint threshold changes event MintThresholdChanged(uint256 instant, uint256 ratified, uint256 multiSig); /// @dev Emitted when mint limits change event MintLimitsChanged(uint256 instant, uint256 ratified, uint256 multiSig); /// @dev Emitted when instant mint pool is refilled event InstantPoolRefilled(); /// @dev Emitted when instant mint pool is ratified event RatifyPoolRefilled(); /// @dev Emitted when multisig mint pool is ratified event MultiSigPoolRefilled(); /* ======================================== Ownership functions ======================================== */ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address payable newOwner) external onlyOwner { pendingOwner = newOwner; emit NewOwnerPending(address(owner), address(pendingOwner)); } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() external onlyPendingOwner { emit OwnershipTransferred(address(owner), address(pendingOwner)); owner = pendingOwner; pendingOwner = address(0); } /* ======================================== proxy functions ======================================== */ function transferTrueCurrencyProxyOwnership(address _newOwner) external onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).transferProxyOwnership(_newOwner); } function claimTrueCurrencyProxyOwnership() external onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).claimProxyOwnership(); } function upgradeTrueCurrencyProxyImplTo(address _implementation) external onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).upgradeTo(_implementation); } /* ======================================== Minting functions ======================================== */ /** * @dev set the threshold for a mint to be considered an instant mint, * ratify mint and multiSig mint. Instant mint requires no approval, * ratify mint requires 1 approval and multiSig mint requires 3 approvals */ function setMintThresholds( uint256 _instant, uint256 _ratified, uint256 _multiSig ) external onlyOwner { require(_instant <= _ratified && _ratified <= _multiSig); instantMintThreshold = _instant; ratifiedMintThreshold = _ratified; multiSigMintThreshold = _multiSig; emit MintThresholdChanged(_instant, _ratified, _multiSig); } /** * @dev set the limit of each mint pool. For example can only instant mint up to the instant mint pool limit * before needing to refill */ function setMintLimits( uint256 _instant, uint256 _ratified, uint256 _multiSig ) external onlyOwner { require(_instant <= _ratified && _ratified <= _multiSig); instantMintLimit = _instant; if (instantMintPool > instantMintLimit) { instantMintPool = instantMintLimit; } ratifiedMintLimit = _ratified; if (ratifiedMintPool > ratifiedMintLimit) { ratifiedMintPool = ratifiedMintLimit; } multiSigMintLimit = _multiSig; if (multiSigMintPool > multiSigMintLimit) { multiSigMintPool = multiSigMintLimit; } emit MintLimitsChanged(_instant, _ratified, _multiSig); } /** * @dev Ratifier can refill instant mint pool */ function refillInstantMintPool() external onlyMintRatifierOrOwner { ratifiedMintPool = ratifiedMintPool.sub(instantMintLimit.sub(instantMintPool)); instantMintPool = instantMintLimit; emit InstantPoolRefilled(); } /** * @dev Owner or 3 ratifiers can refill Ratified Mint Pool */ function refillRatifiedMintPool() external onlyMintRatifierOrOwner { if (msg.sender != owner) { address[2] memory refillApprovals = ratifiedPoolRefillApprovals; require(msg.sender != refillApprovals[0] && msg.sender != refillApprovals[1]); if (refillApprovals[0] == address(0)) { ratifiedPoolRefillApprovals[0] = msg.sender; return; } if (refillApprovals[1] == address(0)) { ratifiedPoolRefillApprovals[1] = msg.sender; return; } } delete ratifiedPoolRefillApprovals; // clears the whole array multiSigMintPool = multiSigMintPool.sub(ratifiedMintLimit.sub(ratifiedMintPool)); ratifiedMintPool = ratifiedMintLimit; emit RatifyPoolRefilled(); } /** * @dev Owner can refill MultiSig Mint Pool */ function refillMultiSigMintPool() external onlyOwner { multiSigMintPool = multiSigMintLimit; emit MultiSigPoolRefilled(); } /** * @dev mintKey initiates a request to mint _value for account _to * @param _to the address to mint to * @param _value the amount requested */ function requestMint(address _to, uint256 _value) external mintNotPaused onlyMintKeyOrOwner { MintOperation memory op = MintOperation(_to, _value, block.number, 0, false); emit RequestMint(_to, _value, mintOperations.length, msg.sender); mintOperations.push(op); } /** * @dev Instant mint without ratification if the amount is less * than instantMintThreshold and instantMintPool * @param _to the address to mint to * @param _value the amount minted */ function instantMint(address _to, uint256 _value) external mintNotPaused onlyMintKeyOrOwner { require(_value <= instantMintThreshold, "over the instant mint threshold"); require(_value <= instantMintPool, "instant mint pool is dry"); instantMintPool = instantMintPool.sub(_value); emit InstantMint(_to, _value, msg.sender); token.mint(_to, _value); } /** * @dev ratifier ratifies a request mint. If the number of * ratifiers that signed off is greater than the number of * approvals required, the request is finalized * @param _index the index of the requestMint to ratify * @param _to the address to mint to * @param _value the amount requested */ function ratifyMint( uint256 _index, address _to, uint256 _value ) external mintNotPaused onlyMintRatifierOrOwner { MintOperation memory op = mintOperations[_index]; require(op.to == _to, "to address does not match"); require(op.value == _value, "amount does not match"); require(!mintOperations[_index].approved[msg.sender], "already approved"); mintOperations[_index].approved[msg.sender] = true; mintOperations[_index].numberOfApproval = mintOperations[_index].numberOfApproval.add(1); emit MintRatified(_index, msg.sender); if (hasEnoughApproval(mintOperations[_index].numberOfApproval, _value)) { finalizeMint(_index); } } /** * @dev finalize a mint request, mint the amount requested to the specified address * @param _index of the request (visible in the RequestMint event accompanying the original request) */ function finalizeMint(uint256 _index) public mintNotPaused { MintOperation memory op = mintOperations[_index]; address to = op.to; uint256 value = op.value; if (msg.sender != owner) { require(canFinalize(_index)); _subtractFromMintPool(value); } delete mintOperations[_index]; token.mint(to, value); emit FinalizeMint(to, value, _index, msg.sender); } /** * assumption: only invoked when canFinalize */ function _subtractFromMintPool(uint256 _value) internal { if (_value <= ratifiedMintPool && _value <= ratifiedMintThreshold) { ratifiedMintPool = ratifiedMintPool.sub(_value); } else { multiSigMintPool = multiSigMintPool.sub(_value); } } /** * @dev compute if the number of approvals is enough for a given mint amount */ function hasEnoughApproval(uint256 _numberOfApproval, uint256 _value) public view returns (bool) { if (_value <= ratifiedMintPool && _value <= ratifiedMintThreshold) { if (_numberOfApproval >= RATIFY_MINT_SIGS) { return true; } } if (_value <= multiSigMintPool && _value <= multiSigMintThreshold) { if (_numberOfApproval >= MULTISIG_MINT_SIGS) { return true; } } if (msg.sender == owner) { return true; } return false; } /** * @dev compute if a mint request meets all the requirements to be finalized * utility function for a front end */ function canFinalize(uint256 _index) public view returns (bool) { MintOperation memory op = mintOperations[_index]; require(op.requestedBlock > mintReqInvalidBeforeThisBlock, "this mint is invalid"); //also checks if request still exists require(!op.paused, "this mint is paused"); require(hasEnoughApproval(op.numberOfApproval, op.value), "not enough approvals"); return true; } /** * @dev revoke a mint request, Delete the mintOperation * @param _index of the request (visible in the RequestMint event accompanying the original request) */ function revokeMint(uint256 _index) external onlyMintKeyOrOwner { delete mintOperations[_index]; emit RevokeMint(_index); } /** * @dev get mint operatino count * @return mint operation count */ function mintOperationCount() public view returns (uint256) { return mintOperations.length; } /* ======================================== Key management ======================================== */ /** * @dev Replace the current mintkey with new mintkey * @param _newMintKey address of the new mintKey */ function transferMintKey(address _newMintKey) external onlyOwner { require(_newMintKey != address(0), "new mint key cannot be 0x0"); emit TransferMintKey(mintKey, _newMintKey); mintKey = _newMintKey; } function setGasRefunder(address refunder) external onlyOwner { gasRefunder = refunder; } function setRegistryAdmin(address admin) external onlyOwner { registryAdmin = admin; } /* ======================================== Mint Pausing ======================================== */ /** * @dev invalidates all mint request initiated before the current block */ function invalidateAllPendingMints() external onlyOwner { mintReqInvalidBeforeThisBlock = block.number; } /** * @dev pause any further mint request and mint finalizations */ function pauseMints() external onlyMintPauserOrOwner { mintPaused = true; emit AllMintsPaused(true); } /** * @dev unpause any further mint request and mint finalizations */ function unpauseMints() external onlyOwner { mintPaused = false; emit AllMintsPaused(false); } /** * @dev pause a specific mint request * @param _opIndex the index of the mint request the caller wants to pause */ function pauseMint(uint256 _opIndex) external onlyMintPauserOrOwner { mintOperations[_opIndex].paused = true; emit MintPaused(_opIndex, true); } /** * @dev unpause a specific mint request * @param _opIndex the index of the mint request the caller wants to unpause */ function unpauseMint(uint256 _opIndex) external onlyOwner { mintOperations[_opIndex].paused = false; emit MintPaused(_opIndex, false); } /* ======================================== set and claim contracts, administrative ======================================== */ /** * @dev Update this contract's token pointer to newContract (e.g. if the * contract is upgraded) */ function setToken(TrueCurrencyWithGasRefund _newContract) external onlyOwner { token = _newContract; emit SetToken(_newContract); } /** * @dev Update this contract's registry pointer to _registry */ function setRegistry(Registry _registry) external onlyOwner { registry = _registry; emit SetRegistry(address(registry)); } /** * @dev Claim ownership of an arbitrary IHasOwner contract */ function issueClaimOwnership(address _other) public onlyOwner { IHasOwner other = IHasOwner(_other); other.claimOwnership(); } /** * @dev Transfer ownership of _child to _newOwner. * Can be used e.g. to upgrade this TokenController contract. * @param _child contract that tokenController currently Owns * @param _newOwner new owner/pending owner of _child */ function transferChild(IHasOwner _child, address _newOwner) external onlyOwner { _child.transferOwnership(_newOwner); emit TransferChild(address(_child), _newOwner); } /** * @dev send all ether in token address to the owner of tokenController */ function requestReclaimEther() external onlyOwner { token.reclaimEther(owner); } /** * @dev transfer all tokens of a particular type in token address to the * owner of tokenController * @param _token token address of the token to transfer */ function requestReclaimToken(IERC20 _token) external onlyOwner { token.reclaimToken(_token, owner); } /** * @dev pause all pausable actions on TrueCurrency, mints/burn/transfer/approve */ function pauseToken() external virtual onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).upgradeTo(PAUSED_IMPLEMENTATION); } /** * @dev Change the minimum and maximum amounts that TrueCurrency users can * burn to newMin and newMax * @param _min minimum amount user can burn at a time * @param _max maximum amount user can burn at a time */ function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner { token.setBurnBounds(_min, _max); } /** * @dev Owner can send ether balance in contract address * @param _to address to which the funds will be send to */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** * @dev Owner can send erc20 token balance in contract address * @param _token address of the token to send * @param _to address to which the funds will be send to */ function reclaimToken(IERC20 _token, address _to) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.transfer(_to, balance); } /** * @dev Owner can allow address to burn tokens * @param burner address of the token that can burn * @param canBurn true if account is allowed to burn, false otherwise */ function setCanBurn(address burner, bool canBurn) external onlyRegistryAdmin { token.setCanBurn(burner, canBurn); emit CanBurn(burner, canBurn); } /** * @dev Set blacklisted status for the account. * @param account address to set blacklist flag for * @param isBlacklisted blacklist flag value */ function setBlacklisted(address account, bool isBlacklisted) external onlyRegistryAdmin { token.setBlacklisted(account, isBlacklisted); } /** * Call hook in `hookContract` with gas refund */ function refundGasWithHook(IHook hookContract) external onlyGasRefunder { // calculate start gas amount uint256 startGas = gasleft(); // call hook hookContract.hook(); // calculate gas used uint256 gasUsed = startGas.sub(gasleft()); // 1 refund = 15,000 gas. EVM refunds maximum half of used gas, so divide by 2. // Add 20% to compensate inter contract communication // (x + 20%) / 2 / 15000 = x / 25000 token.refundGas(gasUsed.div(25000)); } }
Replace the current mintkey with new mintkey _newMintKey address of the new mintKey/
function transferMintKey(address _newMintKey) external onlyOwner { require(_newMintKey != address(0), "new mint key cannot be 0x0"); emit TransferMintKey(mintKey, _newMintKey); mintKey = _newMintKey; }
12,694,008
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import "../../interfaces/IMirinCurve.sol"; import "../../libraries/MathUtils.sol"; /** * @dev Hybrid curve of constant product and constant sum ones (4a(r_0 +r _1) + k = 4ak + (k^3/4r_0r_1)) * Excerpted from https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol * * @author LevX, penandlim(@weeb_mcgee) */ contract HybridCurve is IMirinCurve { using MathUtils for uint256; uint8 private constant PRECISION = 104; // the precision all pools tokens will be converted to uint8 private constant POOL_PRECISION_DECIMALS = 18; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 private constant A_PRECISION = 100; // Swap fee precision. Fees are in increments of 10 bps and cannot be higher than 10%. uint256 private constant SWAP_FEE_PRECISION = 1000; uint256 private constant MAX_SWAP_FEE = 100; function canUpdateData(bytes32 oldData, bytes32 newData) external pure override returns (bool) { (uint8 oldDecimals0, uint8 oldDecimals1, ) = decodeData(oldData); (uint8 newDecimals0, uint8 newDecimals1, uint240 newA) = decodeData(newData); return oldDecimals0 == newDecimals0 && oldDecimals1 == newDecimals1 && newA >= A_PRECISION; } function isValidData(bytes32 data) public pure override returns (bool) { uint8 decimals0 = uint8(uint256(data) >> 248); uint8 decimals1 = uint8((uint256(data) >> 240) % (1 << 8)); uint240 A = uint240(uint256(data)); return decimals0 <= POOL_PRECISION_DECIMALS && decimals1 <= POOL_PRECISION_DECIMALS && A >= A_PRECISION; } function decodeData(bytes32 data) public pure returns ( uint8 decimals0, uint8 decimals1, uint240 A ) { decimals0 = uint8(uint256(data) >> 248); decimals1 = uint8((uint256(data) >> 240) % (1 << 8)); A = uint240(uint256(data)); require( decimals0 <= POOL_PRECISION_DECIMALS && decimals1 <= POOL_PRECISION_DECIMALS && A >= A_PRECISION, "MIRIN: INVALID_DATA" ); } function computeLiquidity( uint256 reserve0, uint256 reserve1, bytes32 data ) external pure override returns (uint256) { (uint8 decimals0, uint8 decimals1, uint240 A) = decodeData(data); uint256[2] memory xp = _xp(reserve0, reserve1, decimals0, decimals1); return _getD(xp, A); } function computePrice( uint112 reserve0, uint112 reserve1, bytes32 data, uint8 tokenIn ) external pure override returns (uint224) { (uint8 decimals0, uint8 decimals1, uint240 A) = decodeData(data); uint256[2] memory xp = _xp(reserve0, reserve1, decimals0, decimals1); uint256 D = _getD(xp, A); uint8 decimals = tokenIn == 0 ? decimals0 : decimals1; return uint224(_getYD(A, tokenIn, xp, D) << (PRECISION / 10**(POOL_PRECISION_DECIMALS - decimals))); } function computeAmountOut( uint256 amountIn, uint112 reserve0, uint112 reserve1, bytes32 data, uint8 swapFee, uint8 tokenIn ) external pure override returns (uint256 amountOut) { require(amountIn > 0, "MIRIN: INSUFFICIENT_INPUT_AMOUNT"); require(reserve0 > 0 && reserve1 > 0, "MIRIN: INSUFFICIENT_LIQUIDITY"); require(swapFee <= MAX_SWAP_FEE, "MIRIN: INVALID_SWAP_FEE"); (uint8 decimals0, uint8 decimals1, uint240 A) = decodeData(data); uint256[2] memory xp = _xp(reserve0, reserve1, decimals0, decimals1); amountIn = amountIn * 10**(POOL_PRECISION_DECIMALS - (tokenIn != 0 ? decimals1 : decimals0)); uint256 x = xp[tokenIn] + amountIn; uint256 y = _getY(x, xp, A); amountOut = xp[1 - tokenIn] - y - 1; amountOut = (amountOut * (SWAP_FEE_PRECISION - swapFee)) / SWAP_FEE_PRECISION; amountOut = amountOut / 10**(POOL_PRECISION_DECIMALS - (tokenIn != 0 ? decimals0 : decimals1)); } function computeAmountIn( uint256 amountOut, uint112 reserve0, uint112 reserve1, bytes32 data, uint8 swapFee, uint8 tokenIn ) external pure override returns (uint256 amountIn) { require(amountOut > 0, "MIRIN: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserve0 > 0 && reserve1 > 0 && (tokenIn != 0 ? reserve0 : reserve1) >= amountOut, "MIRIN: INSUFFICIENT_LIQUIDITY"); require(swapFee <= MAX_SWAP_FEE, "MIRIN: INVALID_SWAP_FEE"); (uint8 decimals0, uint8 decimals1, uint240 A) = decodeData(data); uint256[2] memory xp = _xp(reserve0, reserve1, decimals0, decimals1); amountOut = amountOut * 10**(POOL_PRECISION_DECIMALS - (tokenIn != 0 ? decimals0 : decimals1)); amountOut = (amountOut * SWAP_FEE_PRECISION) / (SWAP_FEE_PRECISION - swapFee); uint256 y = xp[1 - tokenIn] - amountOut; uint256 x = _getY(y, xp, A); amountIn = x + 1 - xp[tokenIn]; amountIn = amountIn / 10**(POOL_PRECISION_DECIMALS - (tokenIn != 0 ? decimals1: decimals0)); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * See the StableSwap paper for details * * @dev Originally https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol#L319 * * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param _A the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function _getD(uint256[2] memory xp, uint256 _A) private pure returns (uint256) { uint256 s = xp[0] + xp[1]; if (s == 0) { return 0; } uint256 prevD; uint256 D = s; uint256 nA = _A * 2; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = ((D**2) / (xp[0] * 2)) * D / (xp[1] * 2); prevD = D; D = (((nA * s / A_PRECISION) + (dP * 2)) * D) / ( (nA - A_PRECISION) * D / A_PRECISION + (dP * 3) ); if (D.within1(prevD)) { return D; } } revert("MIRIN: MAX_LOOP_REACHED"); } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @dev Originally https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol#L432 * * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function _getY( uint256 x, uint256[2] memory xp, uint256 _A ) private pure returns (uint256) { uint256 D = _getD(xp, _A); uint256 nA = 2 * _A; uint256 c = ((D**2) / (x * 2)) * D * A_PRECISION / (nA * 2); uint256 b = x + ((D * A_PRECISION) / nA); uint256 yPrev; uint256 y = D; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = (y**2 + c) / (y * 2 + b - D); if (y.within1(yPrev)) { return y; } } revert("MIRIN: MAX_LOOP_REACHED"); } /** * @notice Calculate the price of a token in the pool given * precision-adjusted balances and a particular D and precision-adjusted * array of balances. * * @dev This is accomplished via solving the quadratic equation iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @dev Originally https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol#L276 * * @param _A the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIn Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param D the stableswap invariant * @return the price of the token, in the same precision as in xp */ function _getYD( uint256 _A, uint8 tokenIn, uint256[2] memory xp, uint256 D ) internal pure returns (uint256) { uint256 nA = 2 * _A; uint256 s = xp[1 - tokenIn]; uint256 c = D**2 / (s * 2); c = (c * D * A_PRECISION) / (nA * 2); uint256 b = s + D * A_PRECISION / nA; uint256 yPrev; uint256 y = D; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = (y ** 2 + c) / (y * 2 + b - D); if (y.within1(yPrev)) { return y; } } revert("MIRIN: MAX_LOOP_REACHED"); } function _xp( uint256 reserve0, uint256 reserve1, uint8 decimals0, uint8 decimals1 ) private pure returns (uint256[2] memory xp) { xp[0] = reserve0 * 10**(POOL_PRECISION_DECIMALS - decimals0); xp[1] = reserve1 * 10**(POOL_PRECISION_DECIMALS - decimals1); return xp; } }
Get D, the StableSwap invariant, based on a set of balances and a particular A. See the StableSwap paper for details xp a precision-adjusted set of pool balances. Array should be the same cardinality as the pool. _A the amplification coefficient n (n - 1) in A_PRECISION. See the StableSwap paper for details return the invariant, at the precision of the pool/
function _getD(uint256[2] memory xp, uint256 _A) private pure returns (uint256) { uint256 s = xp[0] + xp[1]; if (s == 0) { return 0; } uint256 prevD; uint256 D = s; uint256 nA = _A * 2; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = ((D**2) / (xp[0] * 2)) * D / (xp[1] * 2); prevD = D; D = (((nA * s / A_PRECISION) + (dP * 2)) * D) / ( (nA - A_PRECISION) * D / A_PRECISION + (dP * 3) ); if (D.within1(prevD)) { return D; } } revert("MIRIN: MAX_LOOP_REACHED"); }
5,439,610
/* * Copyright 2017-2018 the DCSS authors * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } contract DCSS is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; uint constant buyPriceIndex = 0; uint constant getPriceIndex = 1; uint constant putPriceIndex = 2; // This creates an array with all balances mapping (address => uint256[3]) public storagePriceOf; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function DCSS( uint256 initialSupply, string tokenName, string tokenSymbol, uint256 sellTokenPrice, uint256 buyTokenPrice ) TokenERC20(initialSupply, tokenName, tokenSymbol) public { sellPrice = sellTokenPrice; buyPrice = buyTokenPrice; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function setStoragePrices(address target, uint256 newGetPrice, uint256 newPutPrice, uint256 newReservePrice) public { storagePriceOf[target][getPriceIndex] = newGetPrice; storagePriceOf[target][putPriceIndex] = newPutPrice; storagePriceOf[target][buyPriceIndex] = newReservePrice; } function getStoragePrices(address target) public view returns (uint256) { return storagePriceOf[target][getPriceIndex]; } /// @notice Buy tokens from contract by sending ether function buyIQToken() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sellIQToken(uint256 amount) public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } function buyStorage(address from, address to, uint256 nBytes) public returns (bool success) { uint256 totalCost = nBytes * storagePriceOf[to][buyPriceIndex]; uint256 thirdPartyCost = totalCost * 3 / 100; uint256 renterCost = totalCost - thirdPartyCost; transferFrom(from, to, renterCost); return transferFrom(from, msg.sender, thirdPartyCost); } function buyerPutBytes(address from, address to, uint256 nBytes) public returns (bool success) { uint256 totalCost = nBytes * storagePriceOf[to][putPriceIndex]; uint256 thirdPartyCost = totalCost * 3 / 100; uint256 renterCost = totalCost - thirdPartyCost; transferFrom(from, to, renterCost); return transferFrom(from, msg.sender, thirdPartyCost); } function buyerGetBytes(address from, address to, uint256 nBytes) public returns (bool success) { uint256 totalCost = nBytes * storagePriceOf[to][getPriceIndex]; uint256 thirdPartyCost = totalCost * 3 / 100; uint256 renterCost = totalCost - thirdPartyCost; transferFrom(from, to, renterCost); return transferFrom(from, msg.sender, thirdPartyCost); } }
Set allowance for other address and notify Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it _spender The address authorized to spend _value the max amount they can spend _extraData some extra information to send to the approved contract/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
12,638,171
./full_match/1/0x19bFC3E2De100908DB81C82fdB28205c3b96A4D4/sources/project_/contracts/ThePirateBay.sol
returns the amount of tokens earned account address of the account
function earned(address account) public view returns (uint256 _earned) { uint256 multiplier = totalMultiplier(account); return multiplier * totalReward / totalMultipliers; }
4,839,217
pragma solidity 0.5.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end 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)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) 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 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) 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 SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function SETCOLLATERAL164(CollateralInterface col_) external {
1,784,192
// SPDX-License-Identifier: MIT pragma solidity ^0.4.23; 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); } 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); } /** * @dev A token holder contract that will allow a beneficiary to extract the * tokens after a given release time. * * Useful for simple vesting schedules like "advisors get all of their tokens * after 1 year". */ contract TokenTimelock { struct Timelock { uint256 amount; // amount of tokens to lock uint256 releaseTime; // timestamp when token release is enabled } // tokenAddress => ( ownerAddress => { amount, releaseTime } ) mapping(address => mapping(address => Timelock)) public timelockMap; event TokenTimelocked(ERC20 indexed token, address indexed tokenOwner, uint256 amount, uint256 releaseTime); event TokenTimelockReleased(ERC20 indexed token, address indexed tokenOwner, uint256 amount, uint256 releaseTime, uint256 blockTime); constructor () public {} /** * @return the amount of tokens locked by the tokenOwner. */ function getTokenOwnerLockAmount(ERC20 token, address tokenOwner) public view returns (uint256) { return timelockMap[address(token)][tokenOwner].amount; } /** * @return the releaseTime set by the tokenOwner. */ function getTokenOwnerLockReleaseTime(ERC20 token, address tokenOwner) public view returns (uint256) { return timelockMap[address(token)][tokenOwner].releaseTime; } /** * @notice Locks senders tokens for the specified time * Must approve the contract for transfering tokens before calling this function */ function lock(ERC20 token, uint256 amount, uint256 releaseTime) public returns (bool) { require(releaseTime > block.timestamp, "release time is before current time"); require(amount > 0, "token amount is invalid"); address _tokenOwner = msg.sender; address _tokenAddr = address(token); require(_tokenAddr != address(0), "token address is invalid"); Timelock storage _lock = timelockMap[_tokenAddr][_tokenOwner]; require(_lock.amount == 0 && _lock.releaseTime == 0, "a lock for the token & sender already exists"); require(token.transferFrom(_tokenOwner, address(this), amount), "transferFrom failed"); timelockMap[_tokenAddr][_tokenOwner] = Timelock(amount, releaseTime); emit TokenTimelocked(token, _tokenOwner, amount, releaseTime); return true; } /** * @notice Transfers tokens held by timelock to tokenOwner. */ function release(ERC20 token) public returns (bool) { address _tokenAddr = address(token); address _tokenOwner = msg.sender; require(_tokenAddr != address(0), "token address is invalid"); Timelock storage _lock = timelockMap[_tokenAddr][_tokenOwner]; require(_lock.amount > 0 && _lock.releaseTime > 0, "a lock for the token & sender doesn't exist"); require(block.timestamp >= _lock.releaseTime, "current time is before release time"); uint256 balance = token.balanceOf(address(this)); require(_lock.amount <= balance, "not enough tokens to release"); require(token.transfer(_tokenOwner, _lock.amount), "transfer failed"); timelockMap[_tokenAddr][_tokenOwner].amount = 0; timelockMap[_tokenAddr][_tokenOwner].releaseTime = 0; emit TokenTimelockReleased(token, _tokenOwner, _lock.amount, _lock.releaseTime, block.timestamp); return true; } }
Locks senders tokens for the specified time Must approve the contract for transfering tokens before calling this function/
function lock(ERC20 token, uint256 amount, uint256 releaseTime) public returns (bool) { require(releaseTime > block.timestamp, "release time is before current time"); require(amount > 0, "token amount is invalid"); address _tokenOwner = msg.sender; address _tokenAddr = address(token); require(_tokenAddr != address(0), "token address is invalid"); Timelock storage _lock = timelockMap[_tokenAddr][_tokenOwner]; require(_lock.amount == 0 && _lock.releaseTime == 0, "a lock for the token & sender already exists"); require(token.transferFrom(_tokenOwner, address(this), amount), "transferFrom failed"); timelockMap[_tokenAddr][_tokenOwner] = Timelock(amount, releaseTime); emit TokenTimelocked(token, _tokenOwner, amount, releaseTime); return true; }
10,851,177
pragma solidity ^0.4.24; // File: contracts/FiatTokenV1.sol /** * @title Ownable * @dev The Ownable contract from https://github.com/zeppelinos/labs/blob/master/upgradeability_ownership/contracts/ownership/Ownable.sol * branch: master commit: 3887ab77b8adafba4a26ace002f3a684c1a3388b modified to: * 1) Add emit prefix to OwnershipTransferred event (7/13/18) * 2) Replace constructor with constructor syntax (7/13/18) * 3) consolidate OwnableStorage into this contract */ contract Ownable { // Owner of the contract address private _owner; /** * @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 OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() public { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return _owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { _owner = newOwner; } /** * @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); setOwner(newOwner); } } // File: contracts/Blacklistable.sol /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require(msg.sender == blacklister); _; } /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require(blacklisted[_account] == false); _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) public view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function blacklist(address _account) public onlyBlacklister { blacklisted[_account] = true; emit Blacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function unBlacklist(address _account) public onlyBlacklister { blacklisted[_account] = false; emit UnBlacklisted(_account); } function updateBlacklister(address _newBlacklister) public onlyOwner { require(_newBlacklister != address(0)); blacklister = _newBlacklister; emit BlacklisterChanged(blacklister); } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * Based on openzeppelin tag v1.10.0 commit: feb665136c0dae9912e08397c1a21c4af3651ef3 * Modifications: * 1) Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2) Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3) Removed whenPaused (6/14/2018) * 4) Switches ownable library to use zeppelinos (7/12/18) * 5) Remove constructor (7/13/18) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); address public pauser; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { require(msg.sender == pauser); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyPauser public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyPauser public { paused = false; emit Unpause(); } /** * @dev update the pauser role */ function updatePauser(address _newPauser) onlyOwner public { require(_newPauser != address(0)); pauser = _newPauser; emit PauserChanged(pauser); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/FiatToken.sol /** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by any account other than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by any account other than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * @param minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks if account is a minter * @param account The address to check */ function isMinter(address account) public view returns (bool) { return minters[account]; } /** * @dev Get allowed amount for an account * @param owner address The account owner * @param spender address The account spender */ function allowance(address owner, address spender) public view returns (uint256) { return allowed[owner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) public view returns (uint256) { return balances[account]; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another. * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) whenNotPaused notBlacklisted(_to) notBlacklisted(msg.sender) notBlacklisted(_from) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * @param minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
Function to add/update a new minter minter The address of the minter minterAllowedAmount The minting amount allowed for the minter return True if the operation was successful./
function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; }
15,802,233
./partial_match/1/0x3Bf26541b28A19D31f26cAC34E7CDC0912347ce5/sources/DojimaRiceMarket.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Dojima Rice Market", "DRM") { 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 = 2; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 0; uint256 totalSupply = 250_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = 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);
2,840,478
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './MixinLockCore.sol'; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; /** * @title Mixin for managing `Key` data, as well as the * Approval related functions needed to meet the ERC721 * standard. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinKeys is MixinLockCore { address public tetherContractAddress; function _initializeMixinKeys(address _tetherContractAddress) internal { tetherContractAddress = _tetherContractAddress; } event KeyManagerChanged(uint indexed _tokenId, address indexed _newManager); // Keys // Each owner can have at most exactly one key // TODO: could we use public here? (this could be confusing though because it getter will // return 0 values when missing a key) mapping (address => uint) internal keyByOwner; // Each tokenId can have at most exactly one owner at a time. // Returns 0 if the token does not exist // TODO: once we decouple tokenId from owner address (incl in js), then we can consider // merging this with totalSupply into an array instead. mapping (uint => address) internal _ownerOf; // A given key has both an owner and a manager. // If keyManager == address(0) then the key owner is also the manager // Each key can have at most 1 keyManager. mapping (uint => address) public keyManagerOf; // Keeping track of approved transfers // This is a mapping of addresses which have approved // the transfer of a key to another address where their key can be transferred // Note: the approver may actually NOT have a key... and there can only // be a single approved address mapping (uint => address) private approved; // Keeping track of approved operators for a given Key manager. // This approves a given operator for all keys managed by the calling "keyManager" // The caller may not currently be the keyManager for ANY keys. // These approvals are never reset/revoked automatically, unlike "approved", // which is reset on transfer. mapping (address => mapping (address => bool)) private managerToOperatorApproved; // Ensure that the caller is the keyManager of the key // or that the caller has been approved // for ownership of that key modifier onlyKeyManagerOrApproved( uint _tokenId ) { require( _isKeyManager(_tokenId, msg.sender) || _isApproved(_tokenId, msg.sender) || isApprovedForAll(_ownerOf[_tokenId], msg.sender), 'ONLY_KEY_MANAGER_OR_APPROVED' ); _; } // Ensures that an owner owns or has owned a key in the past modifier ownsOrHasOwnedKey( address _keyOwner ) { require( keyByOwner[_keyOwner] > 0, 'HAS_NEVER_OWNED_KEY' ); _; } // Ensures that an owner has a valid key modifier hasValidKey( address _user ) { require( getHasValidKey(_user), 'KEY_NOT_VALID' ); _; } // Ensures that a key has an owner modifier isKey( uint _tokenId ) { require( _ownerOf[_tokenId] != address(0), 'NO_SUCH_KEY' ); _; } // Ensure that the caller owns the key modifier onlyKeyOwner( uint _tokenId ) { require( ownerOf(_tokenId) == msg.sender, 'ONLY_KEY_OWNER' ); _; } /** * In the specific case of a Lock, each owner can own only at most 1 key. * @return The number of NFTs owned by `_keyOwner`, either 0 or 1. */ function balanceOf( address _keyOwner ) public view returns (uint) { require(_keyOwner != address(0), 'INVALID_ADDRESS'); return getHasValidKey(_keyOwner) ? 1 : 0; } /** * Checks if the user has a non-expired key. */ function getHasValidKey( address _keyOwner ) public view returns (bool isValid) { isValid = keyByOwner[_keyOwner] > 0; if (isValid) { return isValid; } if (tetherContractAddress != address(0)) { ERC721 tetherContract = ERC721(tetherContractAddress); return tetherContract.balanceOf(_keyOwner) > 0; } return false; } /** * @notice Find the tokenId for a given user * @return The tokenId of the NFT, else returns 0 */ function getTokenIdFor( address _account ) public view returns (uint) { return keyByOwner[_account]; } // Returns the owner of a given tokenId function ownerOf( uint _tokenId ) public view returns(address) { return _ownerOf[_tokenId]; } /** * @notice Public function for updating transfer and cancel rights for a given key * @param _tokenId The id of the key to assign rights for * @param _keyManager The address with the manager's rights for the given key. * Setting _keyManager to address(0) means the keyOwner is also the keyManager */ function setKeyManagerOf( uint _tokenId, address _keyManager ) public isKey(_tokenId) { require( _isKeyManager(_tokenId, msg.sender) || isLockManager(msg.sender), 'UNAUTHORIZED_KEY_MANAGER_UPDATE' ); _setKeyManagerOf(_tokenId, _keyManager); } function setTetherContractAddress( address _tetherContractAddress ) public onlyLockManager { tetherContractAddress = _tetherContractAddress; } function _setKeyManagerOf( uint _tokenId, address _keyManager ) internal { if(keyManagerOf[_tokenId] != _keyManager) { keyManagerOf[_tokenId] = _keyManager; _clearApproval(_tokenId); emit KeyManagerChanged(_tokenId, _keyManager); } } /** * This approves _approved to get ownership of _tokenId. * Note: that since this is used for both purchase and transfer approvals * the approved token may not exist. */ function approve( address _approved, uint _tokenId ) public onlyIfAlive onlyKeyManagerOrApproved(_tokenId) { require(msg.sender != _approved, 'APPROVE_SELF'); approved[_tokenId] = _approved; emit Approval(_ownerOf[_tokenId], _approved, _tokenId); } /** * @notice Get the approved address for a single NFT * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for * @return The approved address for this NFT, or the zero address if there is none */ function getApproved( uint _tokenId ) public view isKey(_tokenId) returns (address) { address approvedRecipient = approved[_tokenId]; return approvedRecipient; } function _recordOwner( address _keyOwner, uint _tokenId ) internal { keyByOwner[_keyOwner] = _tokenId; _ownerOf[_tokenId] = _keyOwner; } /** * @dev Tells whether an operator is approved by a given keyManager * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { uint tokenId = keyByOwner[_owner]; address keyManager = keyManagerOf[tokenId]; if(keyManager == address(0)) { return managerToOperatorApproved[_owner][_operator]; } else { return managerToOperatorApproved[keyManager][_operator]; } } /** * Returns true if _keyManager is the manager of the key * identified by _tokenId */ function _isKeyManager( uint _tokenId, address _keyManager ) internal view returns (bool) { if(keyManagerOf[_tokenId] == _keyManager || (keyManagerOf[_tokenId] == address(0) && ownerOf(_tokenId) == _keyManager)) { return true; } else { return false; } } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll( address _to, bool _approved ) public onlyIfAlive { require(_to != msg.sender, 'APPROVE_SELF'); managerToOperatorApproved[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Checks if the given user is approved to transfer the tokenId. */ function _isApproved( uint _tokenId, address _user ) internal view returns (bool) { return approved[_tokenId] == _user; } /** * @dev Function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 _tokenId ) internal { if (approved[_tokenId] != address(0)) { approved[_tokenId] = address(0); } } /** * @dev Change the maximum number of keys the lock can edit * @param _maxNumberOfKeys uint the maximum number of keys */ function setMaxNumberOfKeys (uint _maxNumberOfKeys) external onlyLockManager { require (_maxNumberOfKeys > _totalSupply, "maxNumberOfKeys is smaller than existing supply"); maxNumberOfKeys = _maxNumberOfKeys; } }
Sets or unsets the approval of a given operator An operator is allowed to transfer all tokens of the sender on their behalf _to operator address to set the approval _approved representing the status of the approval to be set/
function setApprovalForAll( address _to, bool _approved ) public onlyIfAlive { require(_to != msg.sender, 'APPROVE_SELF'); managerToOperatorApproved[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); }
7,240,801
./full_match/43113/0x04E9c56359DE02F5384326BC5e975893f628658f/sources/contracts/WOLFI.sol
split amount to fee and transfer amountswap, transfer, liquidity Transfer the amount with 1% from the initial amount reflection fee
function _transfer( address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "WOLFI: transfer from the zero address"); require(recipient != address(0), "WOLFI: transfer to the zero address"); require(amount > 0, "WOLFI: Transfer amount must be greater than zero"); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); (uint256 fee, uint256 transferAmount) = _splitAmount(amount); _transferToExcluded(sender, address(swapManager), fee); _approve(address(swapManager), address(router), fee); swapManager.swap(_DAOWalletAddress, address(this)); _transferStandard(sender, recipient, transferAmount, amount); } }
7,182,065
./full_match/5/0x782D67A65e916CD179761C5c5fc817c1DA57D467/sources/src/zkbob/utils/KycProvidersManagerStorage.sol
Tells the KYC Providers Manager contract address. return res the manager address./
function kycProvidersManager() public view returns (IKycProvidersManager res) { assembly { res := sload(KYC_PROVIDER_MANAGER_STORAGE) } }
11,620,492
//Address: 0xdf68995f07882120b44da1d0fabf41ca1681deec //Contract name: Provide //Balance: 0 Ether //Verification Date: 8/30/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.13; /** * Provide platform contract. */ contract Provide { using SafeMath for uint; /** Provide contract owner; has ability to update the platform robot address. */ address public owner; /** Provide (PRVD) token. */ ProvideToken public token; /** Provide platform robot; has ability to update the wallet contract addresses. */ address public prvd; /** Provide platform wallet where fees owed to Provide are remitted. */ address public prvdWallet; /** Provide platform wallet where payment amounts owed to providers are escrowed. */ address public paymentEscrow; /** * @param _prvd Provide platform robot contract address * @param _prvdWallet Provide platform wallet where fees owed to Provide are remitted * @param _paymentEscrow Provide platform wallet where payment amounts owed to providers are escrowed */ function Provide( address _token, address _prvd, address _prvdWallet, address _paymentEscrow ) { owner = msg.sender; token = ProvideToken(_token); prvd = _prvd; prvdWallet = _prvdWallet; paymentEscrow = _paymentEscrow; } /** * Deploy a work order contract. * @param _peer Address of party purchasing services * @param _identifier Provide platform work order identifier (UUIDv4) */ function createWorkOrder( address _peer, uint128 _identifier ) onlyPrvd returns(address workOrder) { return new ProvideWorkOrder(token, prvd, prvdWallet, paymentEscrow, _peer, _identifier); } /** * Allow the contract owner to update Provide platform robot. */ function setPrvd(address _prvd) onlyOwner { if (_prvd == 0x0) revert(); prvd = _prvd; } /** * Allow the Provide platform robot to update the Provide wallet contract address. */ function setPrvdWallet(address _prvdWallet) onlyPrvd { if (_prvdWallet == 0x0) revert(); prvdWallet = _prvdWallet; } /** * Allow the Provide platform robot to update the payments escrow wallet contract address. */ function setPaymentEscrow(address _paymentEscrow) onlyPrvd { if (_paymentEscrow == 0x0) revert(); paymentEscrow = _paymentEscrow; } /** * Only allow the Provide contract owner to execute a contract function. */ modifier onlyOwner() { if (msg.sender != owner) revert(); _; } /** * Only allow the Provide platform robot to execute a contract function. */ modifier onlyPrvd() { if (msg.sender != prvd) revert(); _; } } /** * Base contract for work orders on the Provide platform. */ contract ProvideWorkOrder { using SafeMath for uint; /** Status of the work order contract. **/ enum Status { Pending, InProgress, Completed, Paid } /** Provide (PRVD) token. */ ProvideToken public token; /** Provide platform robot. */ address public prvd; /** Provide platform wallet where fees owed to Provide are remitted. */ address public prvdWallet; /** Provide platform wallet where payment amounts owed to providers are escrowed. */ address public paymentEscrow; /** Peer requesting and purchasing service. */ address public peer; /** Peer providing service; compensated in PRVD tokens. */ address public provider; /** Provide platform work order identifier (UUIDv4). */ uint128 public identifier; /** Current status of the work order contract. **/ Status public status; /** Total amount of Provide (PRVD) tokens payable to provider, expressed in wei. */ uint256 public amount; /** Encoded transaction details. */ string public details; /** Emitted when the work order has been started. */ event WorkOrderStarted(uint128 _identifier); /** Emitted when the work order has been completed. */ event WorkOrderCompleted(uint128 _identifier, uint256 _amount, string _details); /** Emitted when the transaction has been completed. */ event TransactionCompleted(uint128 _identifier, uint256 _paymentAmount, uint256 feeAmount, string _details); /** * @param _prvd Provide platform robot contract address * @param _paymentEscrow Provide platform wallet where payment amounts owed to providers are escrowed * @param _peer Address of party purchasing services * @param _identifier Provide platform work order identifier (UUIDv4) */ function ProvideWorkOrder( address _token, address _prvd, address _prvdWallet, address _paymentEscrow, address _peer, uint128 _identifier ) { if (_token == 0x0) revert(); if (_prvd == 0x0) revert(); if (_prvdWallet == 0x0) revert(); if (_paymentEscrow == 0x0) revert(); if (_peer == 0x0) revert(); token = ProvideToken(_token); prvd = _prvd; prvdWallet = _prvdWallet; paymentEscrow = _paymentEscrow; peer = _peer; identifier = _identifier; status = Status.Pending; } /** * Set the address of the party providing service and start the work order. * @param _provider Address of the party providing service */ function start(address _provider) public onlyPrvd onlyPending { if (provider != 0x0) revert(); provider = _provider; status = Status.InProgress; WorkOrderStarted(identifier); } /** * Complete the work order. * @param _amount Total amount of Provide (PRVD) tokens payable to provider, expressed in wei * @param _details Encoded transaction details */ function complete(uint256 _amount, string _details) public onlyProvider onlyInProgress { amount = _amount; details = _details; status = Status.Completed; WorkOrderCompleted(identifier, amount, details); } /** * Complete the transaction by remitting the exact amount of PRVD tokens due. * The service provider's payment is escrowed in the payment escrow wallet * and the platform fee is remitted to Provide. * * Partial payments will be rejected. */ function completeTransaction() public onlyPurchaser onlyCompleted { uint allowance = token.allowance(msg.sender, this); if (allowance < amount) revert(); token.transferFrom(this, paymentEscrow, amount); uint feeAmount = allowance.sub(amount); if (feeAmount > 0) token.transferFrom(this, prvdWallet, feeAmount); status = Status.Paid; TransactionCompleted(identifier, amount, feeAmount, details); } /** * Only allow the Provide platform robot to execute a contract function. */ modifier onlyPrvd() { if (msg.sender != prvd) revert(); _; } /** * Only allow the peer purchasing services to execute a contract function. */ modifier onlyPurchaser() { if (msg.sender != peer) revert(); _; } /** * Only allow the service provider to execute a contract function. */ modifier onlyProvider() { if (msg.sender != provider) revert(); _; } /** * Only allow execution of a contract function if the work order is pending. */ modifier onlyPending() { if (uint(status) != uint(Status.Pending)) revert(); _; } /** * Only allow execution of a contract function if the work order is started. */ modifier onlyInProgress() { if (uint(status) != uint(Status.InProgress)) revert(); _; } /** * Only allow execution of a contract function if the work order is complete. */ modifier onlyCompleted() { if (uint(status) != uint(Status.Completed)) revert(); _; } } /** * 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) { return a / b; } 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; } function assertTrue(bool val) internal { assert(val); } function assertFalse(bool val) internal { assert(!val); } } /** * ERC20Basic * Simpler version of ERC20 interface * 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); } /** * ERC20 interface * 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); } /** * Basic token. * Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping (address => uint) balances; /** * Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if (msg.data.length < size + 4) { revert(); } _; } /** * 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); } /** * 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]; } } /** * Standard ERC20 token * * Implemantation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; /** * 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]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * 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)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * 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]; } } /** * Controller interface. */ contract Controller { /** * Called to determine if the token allows proxy payments. * * @param _owner The address that sent ether to the token contract * @return True if the ether is accepted, false if it throws */ function proxyPayment(address _owner) payable returns(bool); /** * Called to determine if the controller approves a token transfer. * * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint _amount) returns(bool); /** * Called to notify the controller of a transfer approval. * * @param _owner The address that calls `approve()` * @param _spender The spender in the `approve()` call * @param _amount The amount in the `approve()` call * @return False if the controller does not authorize the approval */ function onApprove(address _owner, address _spender, uint _amount) returns(bool); } /** * Controlled. */ contract Controlled { address public controller; function Controlled() { controller = msg.sender; } function changeController(address _controller) onlyController { controller = _controller; } modifier onlyController { if (msg.sender != controller) revert(); _; } } /** * A trait that allows any token owner to decrease the token supply. * * We add a Burned event to differentiate from normal transfers. * However, we still try to support some legacy Ethereum ecosystem, * as ERC-20 has not standardized on the burn event yet. */ contract BurnableToken is StandardToken { address public constant BURN_ADDRESS = 0; event Burned(address burner, uint burnedAmount); /** * Burn extra tokens from a balance. * * Keeps token balance tracking services happy by sending the burned * amount to BURN_ADDRESS, so that it will show up as a ERC-20 transaction * in etherscan, etc. as there is no standardized burn event yet. * * @param burnAmount The amount of tokens to burn */ function burn(uint burnAmount) { address burner = msg.sender; balances[burner] = balances[burner].sub(burnAmount); totalSupply = totalSupply.sub(burnAmount); Burned(burner, burnAmount); Transfer(burner, BURN_ADDRESS, burnAmount); } } /** * Mintable token. * * Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Controlled { event Mint(address indexed to, uint value); event MintFinished(); bool public mintingFinished = false; uint public totalSupply = 0; /** * Function to mint tokens * @param _to The address that will recieve 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, uint _amount) onlyController canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyController returns (bool) { mintingFinished = true; MintFinished(); return true; } modifier canMint() { if (mintingFinished) revert(); _; } } /** * LimitedTransferToken * * LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: */ contract LimitedTransferToken is ERC20 { /** * Checks whether it can transfer or otherwise throws */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, uint64(now))) revert(); _; } /** * Checks modifier and allows transfer if tokens are not locked. * * @param _to The address that will recieve the tokens * @param _value The amount of tokens to be transferred */ function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { super.transfer(_to, _value); } /** * Checks modifier and allows transfer if tokens are not locked. * * @param _from The address that will send the tokens * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) { super.transferFrom(_from, _to, _value); } /** * Default transferable tokens function returns all tokens for a holder (no limit). * * Overriding transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. * * @param holder The address of the token holder */ function transferableTokens(address holder, uint64 /* time */) constant public returns (uint256) { return balanceOf(holder); } } /** * Upgrade agent interface. * * Upgrade agent transfers tokens to a new contract. The upgrade agent itself * can be the token contract, or just an intermediary contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; 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. * */ contract UpgradeableToken is StandardToken { /** Contract/actor who can set the upgrade path. */ address public upgradeController; /** Designated upgrade agent responsible for completing the upgrade. */ UpgradeAgent public upgradeAgent; /** Number of tokens upgraded to date. */ uint256 public totalUpgraded; /** * Upgrade states: * * - NotAllowed: the child contract has not reached a condition where the upgrade can begin * - WaitingForAgent: token allows upgrade, but we don'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} /** * Emitted when a token holder upgrades some portion of token holdings. */ event Upgrade(address indexed from, address indexed to, uint256 value); /** * New upgrade agent has been set. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade controller. */ function UpgradeableToken(address _upgradeController) { upgradeController = _upgradeController; } /** * 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)) { revert(); // called in an invalid state } if (value == 0) revert(); // validate input value balances[msg.sender] = balances[msg.sender].sub(value); // Take tokens out from circulation totalSupply = totalSupply.sub(value); totalUpgraded = totalUpgraded.add(value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that can handle. */ function setUpgradeAgent(address agent) external { if (!canUpgrade()) { revert(); } if (agent == 0x0) revert(); if (msg.sender != upgradeController) revert(); // only upgrade controller can designate the next agent if (getUpgradeState() == UpgradeState.Upgrading) revert(); // upgrade has already started for an agent upgradeAgent = UpgradeAgent(agent); if (!upgradeAgent.isUpgradeAgent()) revert(); // bad interface if (upgradeAgent.originalSupply() != totalSupply) revert(); // ensure that token supplies match in source and target UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x0) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade controller. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeController(address controller) public { if (controller == 0x0) revert(); if (msg.sender != upgradeController) revert(); upgradeController = controller; } /** * Child contract can override to condition enable upgrade path. */ function canUpgrade() public constant returns(bool) { return true; } } /** * Vested token. * * Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * Grant tokens to a specified address. * * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. * @param _revokable bool If the grant is revokable. * @param _burnsOnRevoke bool When true, the tokens are burned if revoked. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { revert(); } if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) revert(); // To prevent a user being spammed and have his balance // locked (out of gas attack when calculating vesting). uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * Revoke the grant of tokens of a specified address. * * @param _holder The address which will have its tokens revoked * @param _grantId The id of the token grant */ function revokeTokenGrant(address _holder, uint _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; if (!grant.revokable) { // check if grant is revokable revert(); } if (grant.granter != msg.sender) { // only granter to revoke the grant revert(); } address receiver = grant.burnsOnRevoke ? 0x0 : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * Calculate the total amount of transferable tokens of a holder at a given time. * * @param holder address The address of the holder * @param time uint64 The specific time * @return An uint representing a holder's total amount of transferable tokens */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = nonVested.add(nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = balanceOf(holder).sub(nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * Check the amount of grants that an address has. * * @param _holder The holder of the grants * @return A uint representing the total amount of grants */ function tokenGrantsCount(address _holder) constant returns (uint index) { return grants[_holder].length; } /** * Calculate amount of vested tokens at a specific time. * * @param tokens uint256 The amount of tokens granted * @param time uint64 The time to be checked * @param start uint64 A time representing the beginning of the grant * @param cliff uint64 The cliff period * @param vesting uint64 The vesting period * @return An uint representing the amount of vested tokens from a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . |(grants[_holder] == address(0)) return 0; * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens(uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) uint vestedTokens = tokens.mul(time.sub(start)).div(vesting.sub(start)); return vestedTokens; } /** * Get all information about a specifc grant. * * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * Get the amount of vested tokens at a specific time. * * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * Calculate the amount of non vested tokens at a specific time. * * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * Calculate the date when the holder can trasfer all its tokens * * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = SafeMath.max64(grants[holder][i].vesting, date); } } } /** * Provide (PRVD) token contract. */ contract ProvideToken is BurnableToken, MintableToken, VestedToken, UpgradeableToken { string public constant name = 'Provide'; string public constant symbol = 'PRVD'; uint public constant decimals = 8; function ProvideToken() UpgradeableToken(msg.sender) { } function() public payable { if (isContract(controller)) { if (!Controller(controller).proxyPayment.value(msg.value)(msg.sender)) revert(); } else { revert(); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size > 0; } }
Deploy a work order contract. _peer Address of party purchasing services _identifier Provide platform work order identifier (UUIDv4)/
function createWorkOrder( address _peer, uint128 _identifier ) onlyPrvd returns(address workOrder) { return new ProvideWorkOrder(token, prvd, prvdWallet, paymentEscrow, _peer, _identifier); }
7,215,153
pragma solidity >=0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; using SafeMath for uint8; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 contractBalance = 0; // stors the contract balance struct Airline { bool isRegistered; bool isAutorised; bytes32 name; uint256 balance; } mapping (address => bool) authorizedCaller; // list of address authorize to call the contract Data mapping (address => Airline) private registeredAirlines; // airlines registred to the contract uint256 private airlinesCounter = 0; // stors the number of registered airlines struct Flight { address airline; bytes32 flightNumber; uint256 timestamp; uint8 statusCode; } bytes32[] private flightKeys; // liste of flight keys created in this contract mapping (bytes32 => Flight) private flights; // flight key => Flight details mapping struct Insurance { address passenger; uint256 value; bool paid; } mapping (bytes32 => bytes32[]) private flightInsurances; // flight key => insurance keys related to the flight mapping (bytes32 => Insurance) private insurances; // insurance Key => Insurance details mapping mapping (address => uint256) private passengerBalances; // balance for each insured passenger /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirLineRegistrated(address _airlineAddress); event ContractFunded(uint256 _fundAmount, address _airlineAddress); event NewFlightAdded(address _airlineAddress, bytes32 _flightNumber, uint256 _timestamp, uint8 _status); event InsurancePurchased(bytes32 _flightKey, address _passengerAddress, uint256 _amount); event PassengerPaid(address _passenger, uint256 _amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor (bytes32 _firstAirlineNmae) public { contractOwner = msg.sender; registeredAirlines[msg.sender] = Airline({ isRegistered : true, isAutorised: false, name: _firstAirlineNmae, balance : 0 }); airlinesCounter = airlinesCounter.add(1); } /** * @dev fall back function * */ function () external payable { } /********************************************************************************************/ /* 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"); _; } /** * @dev Modifier that requires the function caller to be registerated to be able te register a new airline */ modifier requireIsRegistered() { require(registeredAirlines[msg.sender].isRegistered || authorizedCaller[msg.sender], "Caller is not registred"); _; } /** * @dev Modifier that requires the airline is not already registered */ modifier requireIsNotRegistered(address _airlineAddress) { require(!registeredAirlines[_airlineAddress].isRegistered, "Airline is already registered"); _; } /** * @dev Modifier that requires the function caller to be autorised to be able te participate in the smart contract */ modifier requireIsAuthorized() { require(registeredAirlines[msg.sender].isAutorised || authorizedCaller[msg.sender], "Caller is not autorised, you have to fund first"); _; } /** * @dev Modifier that requires the flight does not exist to be added */ modifier requireFlightNotExists(address _airlineAddress, bytes32 _flightNumber, uint256 _timestamp) { bytes32 key = generateKey(_airlineAddress, _flightNumber, _timestamp); require(flights[key].airline == address(0), 'Flight already registered'); _; } /** * @dev Modifier that requires the flight exists */ modifier requireFlightExists(bytes32 _flightKey) { require(flights[_flightKey].airline != address(0), 'Flight does not exist'); _; } /** * @dev Modifier that requires the insurance does not exist to be purshaced. */ modifier requireNotInsured(address _passengerAddress, bytes32 _flightKey) { bytes32 insuranceKey = generateKey(_passengerAddress, _flightKey, 0); require(insurances[insuranceKey].passenger == address(0), 'Insurrance already exists for this flight'); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus (bool _mode) external requireContractOwner { operational = _mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address _airlineAddress, bytes32 _airlineName) external requireIsOperational requireIsNotRegistered(_airlineAddress) requireIsRegistered { require(_airlineAddress != address(0), 'The airline Address is not valid'); registeredAirlines[_airlineAddress] = Airline({ isRegistered : true, isAutorised: false, name: _airlineName, balance : 0 }); airlinesCounter = airlinesCounter.add(1); emit AirLineRegistrated(_airlineAddress); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(uint256 _fundAmount, address _airlineAddress) public payable requireIsOperational requireIsRegistered { registeredAirlines[_airlineAddress].balance = registeredAirlines[_airlineAddress].balance.add(_fundAmount); registeredAirlines[_airlineAddress].isAutorised = true; //address payable contractAddress = address(uint160(address(this))); //contractAddress.transfer(_fundAmount); contractBalance = contractBalance.add(_fundAmount); emit ContractFunded(_fundAmount, _airlineAddress); } /** * @dev add new flight by an airline * */ function addNewFlight(address _airlineAddress, bytes32 _flightNumber, uint256 _timestamp, uint8 _status) external requireIsOperational requireIsRegistered requireIsAuthorized requireFlightNotExists(_airlineAddress, _flightNumber, _timestamp) { bytes32 key = generateKey(_airlineAddress, _flightNumber, _timestamp); flights[key] = Flight({ airline: _airlineAddress, flightNumber: _flightNumber, timestamp: _timestamp, statusCode: _status }); flightKeys.push(key); emit NewFlightAdded(_airlineAddress, _flightNumber, _timestamp, _status); } /** * @dev Buy insurance for a flight * */ function buy(bytes32 _flightKey, address _passengerAddress, uint256 _amount) external payable requireIsOperational requireIsAuthorized requireFlightExists(_flightKey) requireNotInsured(_passengerAddress, _flightKey) { bytes32 insuranceKey = generateKey(_passengerAddress, _flightKey, 0); insurances[insuranceKey] = Insurance(_passengerAddress, _amount, false); flightInsurances[_flightKey].push(insuranceKey); registeredAirlines[flights[_flightKey].airline].balance = registeredAirlines[flights[_flightKey].airline].balance.add(_amount); //address(this).transfer(_amount); contractBalance = contractBalance.add(_amount); emit InsurancePurchased(_flightKey, _passengerAddress, _amount); } /** * @dev credits all ensurees for the given flight (flight key) * */ function creditInsurees(bytes32 _flightKey, uint256 _multiplier) external requireIsOperational requireIsAuthorized { address airlineAddress = flights[_flightKey].airline; for (uint i = 0; i < flightInsurances[_flightKey].length; i++) { Insurance storage insurance = insurances[flightInsurances[_flightKey][i]]; if (insurance.paid == false) { uint256 amount = insurance.value.mul(_multiplier).div(100); creditInsuree(insurance, amount); registeredAirlines[airlineAddress].balance = registeredAirlines[airlineAddress].balance.sub(amount); } } } /** * @dev Credits payouts to insuree * */ function creditInsuree (Insurance storage _insurance, uint256 _amount) private requireIsOperational requireIsAuthorized { require (!_insurance.paid, "This insurance has already been paid"); passengerBalances[_insurance.passenger] = passengerBalances[_insurance.passenger].add(_amount); _insurance.paid = true; } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address _passenger, uint256 _amount) external payable requireIsOperational requireIsAuthorized { require(contractBalance >= _amount, "The contract balance is not sufficient to pay the insured passenger"); require(passengerBalances[_passenger] >= _amount, "The desired amount exceedes the amount owed by the passenger"); address payable payablePassengerAddress = address(uint160(_passenger)); uint256 passengerCurrentBalance = passengerBalances[_passenger]; uint256 newBalance = passengerCurrentBalance.sub(_amount); passengerBalances[_passenger] = newBalance; payablePassengerAddress.transfer(_amount); contractBalance = contractBalance.sub(_amount); emit PassengerPaid(_passenger, _amount); } /** * @dev Update the flight status * */ function setFlightStatus(bytes32 _flightKey, uint8 _statusCode) external requireIsOperational requireIsAuthorized { flights[_flightKey].statusCode = _statusCode; } /** * @dev returns the number of the airlines registred to the contract * */ function getAirlinesNumber() external view requireIsOperational returns(uint256) { return airlinesCounter; } /** * @dev returns the number of the airlines registred to the contract * */ function getContractBalance() external view requireIsOperational requireContractOwner returns(uint256) { return contractBalance; } /** * @dev returns all the airlines registred to the contract * */ function getAllFlights() external view requireIsOperational requireIsAuthorized returns(bytes32[] memory) { bytes32[] memory flightsRegistred = new bytes32[](flightKeys.length); for (uint i = 0; i < flightKeys.length; i++){ flightsRegistred[i] = flights[flightKeys[i]].flightNumber; } return flightsRegistred; } /** * @dev returns the passenger balance if exists * */ function getPassengerBalance(address _passengerAddress) external view requireIsOperational returns(uint256) { return passengerBalances[_passengerAddress]; } /** * @dev Authorize one address contract to use all this contract's methonds * @param _callerAddress The new authorized contract's address */ function authorizeCaller(address _callerAddress) external requireIsOperational requireContractOwner { authorizedCaller[_callerAddress] = true; } function generateKey(address _airlineAddress, bytes32 _flight, uint256 _timestamp) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_airlineAddress, _flight, _timestamp)); } /** * @dev fetch Flight details * */ function fetchFlightDetails(bytes32 _flightNumber) external view requireIsOperational returns ( address airline, bytes32 flightNumber, uint256 timestamp, uint8 statusCode, bytes32 flightKey ) { Flight storage flight = flights[bytes32(0)]; flightKey = bytes32(0); for (uint8 i = 0; i < flightKeys.length; i++){ if(flights[flightKeys[i]].flightNumber == _flightNumber){ flight = flights[flightKeys[i]]; flightKey = flightKeys[i]; break; } } airline = flight.airline; flightNumber = flight.flightNumber; timestamp = flight.timestamp; statusCode = flight.statusCode; return ( airline, flightNumber, timestamp, statusCode, flightKey) ; } /** * @dev fetch Airline details * @param _airlineAddress the airline address to fetch * */ function fetchAirlineDetails(address _airlineAddress) external view requireIsOperational returns ( bool isRegistered, bool isAutorised, bytes32 name, uint256 balance ) { Airline storage airline = registeredAirlines[_airlineAddress]; isRegistered = airline.isRegistered; isAutorised = airline.isAutorised; name = airline.name; balance = airline.balance; return (isRegistered, isAutorised, name, balance); } /** * @dev fetch Insuree details * */ function fetchInsuranceDetails(bytes32 _flightKey, address _passengerAddress) external view requireIsOperational returns ( address passenger, uint256 value, bool paid ) { Insurance storage insurance = insurances[bytes32(0)]; for (uint i = 0; i < flightInsurances[_flightKey].length; i++) { insurance = insurances[flightInsurances[_flightKey][i]]; if (insurance.passenger == _passengerAddress){ insurance = insurances[flightInsurances[_flightKey][i]]; break; } } passenger = insurance.passenger; value = insurance.value; paid = insurance.paid; return (passenger, value, paid); } }
credits all ensurees for the given flight (flight key)/
function creditInsurees(bytes32 _flightKey, uint256 _multiplier) external requireIsOperational requireIsAuthorized { address airlineAddress = flights[_flightKey].airline; for (uint i = 0; i < flightInsurances[_flightKey].length; i++) { Insurance storage insurance = insurances[flightInsurances[_flightKey][i]]; if (insurance.paid == false) { uint256 amount = insurance.value.mul(_multiplier).div(100); creditInsuree(insurance, amount); registeredAirlines[airlineAddress].balance = registeredAirlines[airlineAddress].balance.sub(amount); } } }
12,797,383
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /** * @title StakeAllIndex * @dev Main Contract For DeFi Smart Accounts. This is also a factory contract, Which deploys new Smart Account. * Also Registry for DeFi Smart Accounts. */ interface AccountInterface { function version() external view returns (uint256); function enable(address authority) external; function cast( address[] calldata _targets, bytes[] calldata _datas, address _origin ) external payable returns (bytes32[] memory responses); } interface ListInterface { function init(address _account) external; } contract AddressIndex { event LogNewMaster(address indexed master); event LogUpdateMaster(address indexed master); event LogNewCheck(uint256 indexed accountVersion, address indexed check); event LogNewAccount( address indexed _newAccount, address indexed _connectors, address indexed _check ); // New Master Address. address private newMaster; // Master Address. address public master; // List Registry Address. address public list; // Connectors Modules(Account Module Version => Connectors Registry Module Address). mapping(uint256 => address) public connectors; // Check Modules(Account Module Version => Check Module Address). mapping(uint256 => address) public check; // Account Modules(Account Module Version => Account Module Address). mapping(uint256 => address) public account; // Version Count of Account Modules. uint256 public versionCount; /** * @dev Throws if the sender not is Master Address. */ modifier isMaster() { require(msg.sender == master, "not-master"); _; } /** * @dev Change the Master Address. * @param _newMaster New Master Address. */ function changeMaster(address _newMaster) external isMaster { require(_newMaster != master, "already-a-master"); require(_newMaster != address(0), "not-valid-address"); require(newMaster != _newMaster, "already-a-new-master"); newMaster = _newMaster; emit LogNewMaster(_newMaster); } function updateMaster() external { require(newMaster != address(0), "not-valid-address"); require(msg.sender == newMaster, "not-master"); master = newMaster; newMaster = address(0); emit LogUpdateMaster(master); } /** * @dev Change the Check Address of a specific Account Module version. * @param accountVersion Account Module version. * @param _newCheck The New Check Address. */ function changeCheck(uint256 accountVersion, address _newCheck) external isMaster { require(_newCheck != check[accountVersion], "already-a-check"); check[accountVersion] = _newCheck; emit LogNewCheck(accountVersion, _newCheck); } /** * @dev Add New Account Module. * @param _newAccount The New Account Module Address. * @param _connectors Connectors Registry Module Address. * @param _check Check Module Address. */ function addNewAccount( address _newAccount, address _connectors, address _check ) external isMaster { require(_newAccount != address(0), "not-valid-address"); versionCount++; require( AccountInterface(_newAccount).version() == versionCount, "not-valid-version" ); account[versionCount] = _newAccount; if (_connectors != address(0)) connectors[versionCount] = _connectors; if (_check != address(0)) check[versionCount] = _check; emit LogNewAccount(_newAccount, _connectors, _check); } } contract CloneFactory is AddressIndex { /** * @dev Clone a new Account Module. * @param version Account Module version to clone. */ function createClone(uint256 version) internal returns (address result) { bytes20 targetBytes = bytes20(account[version]); // solium-disable-next-line security/no-inline-assembly assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } /** * @dev Check if Account Module is a clone. * @param version Account Module version. * @param query Account Module Address. */ function isClone(uint256 version, address query) external view returns (bool result) { bytes20 targetBytes = bytes20(account[version]); // solium-disable-next-line security/no-inline-assembly assembly { let clone := mload(0x40) mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } contract StakeAllIndex is CloneFactory { event LogAccountCreated( address sender, address indexed owner, address indexed account, address indexed origin ); /** * @dev Create a new DeFi Smart Account for a user and run cast function in the new Smart Account. * @param _owner Owner of the Smart Account. * @param accountVersion Account Module version. * @param _targets Array of Target to run cast function. * @param _datas Array of Data(callData) to run cast function. * @param _origin Where Smart Account is created. */ function buildWithCast( address _owner, uint256 accountVersion, address[] calldata _targets, bytes[] calldata _datas, address _origin ) external payable returns (address _account) { _account = build(_owner, accountVersion, _origin); if (_targets.length > 0) AccountInterface(_account).cast{value: msg.value}( _targets, _datas, _origin ); } /** * @dev Create a new DeFi Smart Account for a user. * @param _owner Owner of the Smart Account. * @param accountVersion Account Module version. * @param _origin Where Smart Account is created. */ function build( address _owner, uint256 accountVersion, address _origin ) public returns (address _account) { require( accountVersion != 0 && accountVersion <= versionCount, "not-valid-account" ); _account = createClone(accountVersion); ListInterface(list).init(_account); AccountInterface(_account).enable(_owner); emit LogAccountCreated(msg.sender, _owner, _account, _origin); } /** * @dev Setup Initial things for StakeAllIndex, after its been deployed and can be only run once. * @param _master The Master Address. * @param _list The List Address. * @param _account The Account Module Address. * @param _connectors The Connectors Registry Module Address. */ function setBasics( address _master, address _list, address _account, address _connectors ) external { require( master == address(0) && list == address(0) && account[1] == address(0) && connectors[1] == address(0) && versionCount == 0, "already-defined" ); master = _master; list = _list; versionCount++; account[versionCount] = _account; connectors[versionCount] = _connectors; } }
Check if Account Module is a clone. version Account Module version. query Account Module Address./ solium-disable-next-line security/no-inline-assembly
function isClone(uint256 version, address query) external view returns (bool result) { bytes20 targetBytes = bytes20(account[version]); assembly { let clone := mload(0x40) mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } }
13,383,513
pragma solidity >=0.5; pragma experimental ABIEncoderV2; /** * @title DexStatus * @dev Status for Dex */ contract DexStatus { string constant ONLY_RELAYER = "ONLY_RELAYER"; string constant ONLY_AIRDROP = "ONLY_AIRDROP"; string constant ONLY_INACTIVITY = "ONLY_INACTIVITY"; string constant ONLY_WITHDRAWALAPPROVED = "ONLY_WITHDRAWALAPPROVED"; string constant INVALID_NONCE = "INVALID_NONCE"; string constant INVALID_PERIOD = "INVALID_PERIOD"; string constant INVALID_AMOUNT = "INVALID_AMOUNT"; string constant INVALID_TIME = "INVALID_TIME"; string constant INVALID_GASTOKEN = "INVALID_GASTOKEN"; string constant TRANSFER_FAILED = "TRANSFER_FAILED"; string constant ECRECOVER_FAILED = "ECRECOVER_FAILED"; string constant INSUFFICIENT_FOUND = "INSUFFICIENT"; string constant TRADE_EXISTS = "TRADED"; string constant WITHDRAW_EXISTS = "WITHDRAWN"; string constant MAX_VALUE_LIMIT = "MAX_LIMIT"; string constant AMOUNT_EXCEEDED = "AMOUNT_EXCEEDED"; } /** * @title IGasStorage * @dev GasStorage interface to burn and mint gastoken */ interface IGasStorage { function mint(uint256 value) external; function burn(uint256 value) external; function balanceOf() external view returns (uint256 balance); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = tx.origin; } /** * @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; } } /** * @dev ERC20 interface */ interface ERC20 { function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success) ; function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) view external returns (uint256 remaining); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Dex * @dev Smart contract for https://www.dex.io */ contract Dex is Ownable,DexStatus { using SafeMath for uint256; struct Order { address token; address baseToken; address user; uint256 tokenAmount; uint256 baseTokenAmount; uint nonce; uint expireTime; uint maxGasFee; uint timestamp; address gasToken; bool sell; uint8 V; bytes32 R; bytes32 S; uint signType; } struct TradeInfo { uint256 tradeTokenAmount; uint256 tradeTakerFee; uint256 tradeMakerFee; uint256 tradeGasFee; uint tradeNonce; address tradeGasToken; } mapping (address => mapping (address => uint256)) public _balances; mapping (address => uint) public _invalidOrderNonce; mapping (bytes32 => uint256) public _orderFills; mapping (address => bool) public _relayers; mapping (bytes32 => bool) public _traded; mapping (bytes32 => bool) public _withdrawn; mapping (bytes32 => uint256) public _orderGasFee; mapping (address => uint) public _withdrawalApplication; address public _feeAccount; address public _airdropContract; address public _gasStorage; uint256 public _withdrawalApplicationPeriod = 10 days; uint256 public _takerFeeRate = 0.002 ether; uint256 public _makerFeeRate = 0.001 ether; string private constant EIP712DOMAIN_TYPE = "EIP712Domain(string name)"; bytes32 private constant EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712DOMAIN_TYPE)); bytes32 private constant DOMAIN_SEPARATOR = keccak256(abi.encode(EIP712DOMAIN_TYPEHASH,keccak256(bytes("Dex.io")))); string private constant ORDER_TYPE = "Order(address token,address baseToken,uint256 tokenAmount,uint256 baseTokenAmount,uint256 nonce,bool sell,uint256 expireTime,uint256 maxGasFee,address gasToken,uint timestamp)"; bytes32 private constant ORDER_TYPEHASH = keccak256(abi.encodePacked(ORDER_TYPE)); string private constant WITHDRAW_TYPE = "Withdraw(address token,uint256 tokenAmount,address to,uint256 nonce,address feeToken,uint256 feeWithdrawal,uint timestamp)"; bytes32 private constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(WITHDRAW_TYPE)); event Trade(bytes32 takerHash,bytes32 makerHash,uint256 tradeAmount,uint256 tradeBaseTokenAmount,uint256 tradeNonce,uint256 takerCostFee, uint makerCostFee,bool sellerIsMaker,uint256 gasFee); event Balance(uint256 takerBaseTokenBalance,uint256 takerTokenBalance,uint256 makerBaseTokenBalance,uint256 makerTokenBalance); event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance); event Withdraw(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 balance); event Transfer(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 fromBalance,uint256 toBalance); event Airdrop(address indexed to, address indexed token,uint256 amount); event WithdrawalApplication(address user,uint timestamp); modifier onlyRelayer { if (msg.sender != owner && !_relayers[msg.sender]) revert(ONLY_RELAYER); _; } modifier onlyAirdropContract { if (msg.sender != _airdropContract) revert(ONLY_AIRDROP); _; } /** * @dev approved in 10 days */ modifier onlyWithdrawalApplicationApproved { require ( _withdrawalApplication[msg.sender] != uint(0) && block.timestamp - _withdrawalApplicationPeriod > _withdrawalApplication[msg.sender], ONLY_WITHDRAWALAPPROVED); _; } /** * @param feeAccount account to receive the fee */ constructor(address feeAccount) public { _feeAccount = feeAccount; } /** * @dev do no send eth to dex contract directly. */ function() external { revert(); } /** * @dev set a relayer */ function setRelayer(address relayer, bool isRelayer) public onlyOwner { _relayers[relayer] = isRelayer; } /** * @dev check a relayer */ function isRelayer(address relayer) public view returns(bool) { return _relayers[relayer]; } /** * @dev set account that receive the fee */ function setFeeAccount(address feeAccount) public onlyOwner { _feeAccount = feeAccount; } /** * @dev set set maker and taker fee rate * @param makerFeeRate maker fee rate can't be more than 0.5% * @param takerFeeRate taker fee rate can't be more than 0.5% */ function setFee(uint256 makerFeeRate,uint256 takerFeeRate) public onlyOwner { require(makerFeeRate <= 0.005 ether && takerFeeRate <= 0.005 ether,MAX_VALUE_LIMIT); _makerFeeRate = makerFeeRate; _takerFeeRate = takerFeeRate; } /** * @dev set gasStorage contract to save gas */ function setGasStorage(address gasStorage) public onlyOwner { _gasStorage = gasStorage; } /** * @dev set airdrop contract to implement airdrop function */ function setAirdrop(address airdrop) public onlyOwner{ _airdropContract = airdrop; } /** * @dev set withdraw application period * @param period the period can't be more than 10 days */ function setWithdrawalApplicationPeriod(uint period) public onlyOwner { if(period > 10 days ){ return; } _withdrawalApplicationPeriod = period; } /** * @dev invalid the orders before nonce */ function invalidateOrdersBefore(address user, uint256 nonce) public onlyRelayer { if (nonce < _invalidOrderNonce[user]) { revert(INVALID_NONCE); } _invalidOrderNonce[user] = nonce; } /** * @dev deposit token */ function depositToken(address token, uint256 amount) public { require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED); _deposit(msg.sender,token,amount); } /** * @dev deposit token from msg.sender to someone */ function depositTokenTo(address to,address token, uint256 amount) public { require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED); _deposit(to,token,amount); } /** * @dev deposit eth */ function deposit() public payable { _deposit(msg.sender,address(0),msg.value); } /** * @dev deposit eth from msg.sender to someone */ function depositTo(address to) public payable { _deposit(to,address(0),msg.value); } /** * @dev _deposit */ function _deposit(address user,address token,uint256 amount) internal { _balances[token][user] = _balances[token][user].add(amount); emit Deposit(token, user, amount, _balances[token][user]); } /** * @dev submit a withdrawal application, user can not place any orders after submit a withdrawal application */ function submitWithdrawApplication() public { _withdrawalApplication[msg.sender] = block.timestamp; emit WithdrawalApplication(msg.sender,block.timestamp); } /** * @dev cancel withdraw application */ function cancelWithdrawApplication() public { _withdrawalApplication[msg.sender] = 0; emit WithdrawalApplication(msg.sender,0); } /** * @dev check user withdraw application status */ function isWithdrawApplication(address user) view public returns(bool) { if(_withdrawalApplication[user] == uint(0)) { return false; } return true; } /** * @dev withdraw token */ function _withdraw(address from,address payable to,address token,uint256 amount) internal { if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); } _balances[token][from] = _balances[token][from].sub(amount); if(token == address(0)) { to.transfer(amount); }else{ require(ERC20(token).transfer(to, amount),TRANSFER_FAILED); } emit Withdraw(token, from, to, amount, _balances[token][from]); } /** * @dev user withdraw token */ function withdraw(address token) public onlyWithdrawalApplicationApproved { uint256 amount = _balances[token][msg.sender]; if(amount != 0){ _withdraw(msg.sender,msg.sender,token,amount); } } /** * @dev user withdraw many tokens */ function withdrawAll(address[] memory tokens) public onlyWithdrawalApplicationApproved { for(uint256 i = 0; i< tokens.length ;i++){ uint256 amount = _balances[tokens[i]][msg.sender]; if(amount == 0){ continue; } _withdraw(msg.sender,msg.sender,tokens[i],amount); } } /** * @dev user send withdraw request with relayer's authorized signature */ function authorizedWithdraw(address payable to,address token,uint256 amount, uint256 nonce,uint expiredTime,address relayer,uint8 v, bytes32 r,bytes32 s) public { require(_withdrawalApplication[msg.sender] == uint(0)); require(expiredTime >= block.timestamp,INVALID_TIME); require(_relayers[relayer] == true,ONLY_RELAYER); bytes32 hash = keccak256(abi.encodePacked(msg.sender,to, token, amount, nonce, expiredTime)); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) != relayer) { revert(ECRECOVER_FAILED); } _withdraw(msg.sender,to,token,amount); } /** * @dev withdraw the token from Dex Wallet to Etheruem Wallet,signType [0 = signTypeDataV3, 1 = eth_sign] */ function adminWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer { bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; _transfer(from,to,token,amount,feeToken,feeWithdrawal,false); } /** * @dev transfer the token between Dex Wallet,signType [0 = signTypeDataV3, 1 = eth_sign] */ function adminTransfer(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer { bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; _transfer(from,to,token,amount,feeToken,feeWithdrawal,true); } /** * @dev transfer the token * @param from token sender * @param to token receiver * @param token The address of token to transfer * @param amount The amount to transfer * @param feeToken The address of token to pay the fee * @param feeWithdrawal The amount of feeToken to pay the fee * @param isInternal True is transfer token from a Dex Wallet to a Dex Wallet, False is transfer a token from Dex wallet to a Etheruem Wallet */ function _transfer(address from,address payable to,address token,uint256 amount, address feeToken,uint256 feeWithdrawal, bool isInternal) internal { if (feeWithdrawal > 0) { require(_balances[feeToken][from] >= feeWithdrawal, INSUFFICIENT_FOUND ); _balances[feeToken][from] = _balances[feeToken][from].sub(feeWithdrawal); _balances[feeToken][_feeAccount] = _balances[feeToken][_feeAccount].add(feeWithdrawal); } if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); } _balances[token][from] = _balances[token][from].sub(amount); if(isInternal) { _balances[token][to] = _balances[token][to].add(amount); emit Transfer(token, from, to, amount, _balances[token][from], _balances[token][to]); }else{ if(token == address(0)) { to.transfer(amount); }else{ require(ERC20(token).transfer(to, amount),TRANSFER_FAILED); } emit Withdraw(token, from, to, amount, _balances[token][from]); } } /** * @dev mirgate function will withdraw all user token balances to wallet */ function adminWithdrawAll(address payable user,address[] memory tokens) public onlyOwner { for(uint256 i = 0; i< tokens.length ;i++){ address token = tokens[i]; uint256 amount = _balances[token][user]; if(amount == 0){ continue; } _withdraw(user,user,token,amount); } } /** * @dev get the balance of the account */ function balanceOf(address token, address user) public view returns (uint256) { return _balances[token][user]; } /** * @dev trade order only call by relayer, ti.signType: 0 = signTypeDataV3, 1 = eth_sign */ function tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti) public onlyRelayer { uint256 gasInitial = gasleft(); bytes32 takerHash = ecrecoverOrder(taker,taker.signType); bytes32 makerHash = ecrecoverOrder(maker,maker.signType); bytes32 tradeHash = keccak256(abi.encodePacked(takerHash ,makerHash)); require(_traded[tradeHash] == false,TRADE_EXISTS); _traded[tradeHash] = true; _tradeOrder(taker,maker,ti,takerHash,makerHash); uint256 gasUsed = gasInitial - gasleft(); _burnGas(gasUsed); } /** * @dev trade order internal */ function _tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti, bytes32 takerHash,bytes32 makerHash) internal { require(taker.baseToken == maker.baseToken && taker.token == maker.token); require(ti.tradeTokenAmount > 0 , INVALID_AMOUNT ); require((block.timestamp <= taker.expireTime) && (block.timestamp <= maker.expireTime) , INVALID_TIME ); require( (_invalidOrderNonce[taker.user] < taker.nonce) &&(_invalidOrderNonce[maker.user] < maker.nonce),INVALID_NONCE) ; require( (taker.tokenAmount.sub(_orderFills[takerHash]) >= ti.tradeTokenAmount) && (maker.tokenAmount.sub(_orderFills[makerHash]) >= ti.tradeTokenAmount), AMOUNT_EXCEEDED); require(taker.gasToken == ti.tradeGasToken, INVALID_GASTOKEN); uint256 tradeBaseTokenAmount = ti.tradeTokenAmount.mul(maker.baseTokenAmount).div(maker.tokenAmount); (uint256 takerFee,uint256 makerFee) = calcMaxFee(ti,tradeBaseTokenAmount,maker.sell); uint gasFee = ti.tradeGasFee; if(gasFee != 0) { if( taker.maxGasFee < _orderGasFee[takerHash].add(gasFee)) { gasFee = taker.maxGasFee.sub(_orderGasFee[takerHash]); } if(gasFee != 0) { _orderGasFee[takerHash] = _orderGasFee[takerHash].add(gasFee); _balances[taker.gasToken][taker.user] = _balances[taker.gasToken][taker.user].sub(gasFee); } } if( maker.sell) { //maker is seller _updateOrderBalance(taker.user,maker.user,taker.baseToken,taker.token, tradeBaseTokenAmount,ti.tradeTokenAmount,takerFee,makerFee); }else { //maker is buyer _updateOrderBalance(maker.user,taker.user,taker.baseToken,taker.token, tradeBaseTokenAmount,ti.tradeTokenAmount,makerFee,takerFee); } //fill order _orderFills[takerHash] = _orderFills[takerHash].add(ti.tradeTokenAmount); _orderFills[makerHash] = _orderFills[makerHash].add(ti.tradeTokenAmount); emit Trade(takerHash,makerHash,ti.tradeTokenAmount,tradeBaseTokenAmount,ti.tradeNonce,takerFee,makerFee, maker.sell ,gasFee); emit Balance(_balances[taker.baseToken][taker.user],_balances[taker.token][taker.user],_balances[maker.baseToken][maker.user],_balances[maker.token][maker.user]); } /** * @dev update the balance after each order traded */ function _updateOrderBalance(address buyer,address seller,address base,address token,uint256 baseAmount,uint256 amount,uint256 buyFee,uint256 sellFee) internal { _balances[base][seller] = _balances[base][seller].add(baseAmount.sub(sellFee)); _balances[base][buyer] = _balances[base][buyer].sub(baseAmount); _balances[token][buyer] = _balances[token][buyer].add(amount.sub(buyFee)); _balances[token][seller] = _balances[token][seller].sub(amount); _balances[base][_feeAccount] = _balances[base][_feeAccount].add(sellFee); _balances[token][_feeAccount] = _balances[token][_feeAccount].add(buyFee); } /** * @dev calc max fee for maker and taker * @return return a taker and maker fee limit by _takerFeeRate and _makerFeeRate */ function calcMaxFee(TradeInfo memory ti,uint256 tradeBaseTokenAmount,bool sellerIsMaker) view public returns (uint256 takerFee,uint256 makerFee) { uint maxTakerFee; uint maxMakerFee; takerFee = ti.tradeTakerFee; makerFee = ti.tradeMakerFee; if(sellerIsMaker) { // taker is buyer maxTakerFee = (ti.tradeTokenAmount * _takerFeeRate) / 1 ether; maxMakerFee = (tradeBaseTokenAmount * _makerFeeRate) / 1 ether; }else{ // maker is buyer maxTakerFee = (tradeBaseTokenAmount * _takerFeeRate) / 1 ether; maxMakerFee = (ti.tradeTokenAmount * _makerFeeRate) / 1 ether; } if(ti.tradeTakerFee > maxTakerFee) { takerFee = maxTakerFee; } if(ti.tradeMakerFee > maxMakerFee) { makerFee = maxMakerFee; } } /** * @dev get fee Rate */ function getFeeRate() view public returns(uint256 makerFeeRate,uint256 takerFeeRate) { return (_makerFeeRate,_takerFeeRate); } /** * @dev get order filled amount * @param orderHash the order hash * @return return the filled amount for a order */ function getOrderFills(bytes32 orderHash) view public returns(uint256 filledAmount) { return _orderFills[orderHash]; } ///@dev check orders traded function isTraded(bytes32 buyOrderHash,bytes32 sellOrderHash) view public returns(bool traded) { return _traded[keccak256(abi.encodePacked(buyOrderHash, sellOrderHash))]; } /** * @dev Airdrop the token directly to Dex user's walle,only airdrop contract can call this function. * @param to the recipient * @param token the ERC20 token to send * @param amount the token amount to send */ function airdrop(address to,address token,uint256 amount) public onlyAirdropContract { //Not EOA require(tx.origin != msg.sender); require(_balances[token][msg.sender] >= amount ,INSUFFICIENT_FOUND); _balances[token][msg.sender] = _balances[token][msg.sender].sub(amount); _balances[token][to] = _balances[token][to].add(amount); emit Airdrop(to,token,amount); } /** * @dev ecreover the order sign * @return return a order hash */ function ecrecoverOrder(Order memory order,uint signType) public pure returns (bytes32 orderHash) { if(signType == 0 ) { orderHash = keccak256(abi.encode( ORDER_TYPEHASH, order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)),order.V,order.R, order.S) != order.user) { revert(ECRECOVER_FAILED); } }else { orderHash = keccak256(abi.encodePacked(order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp)); if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",orderHash)),order.V,order.R, order.S) != order.user) { revert(ECRECOVER_FAILED); } } } /** * @dev ecrecover the withdraw sign * @return return a withdraw hash */ function ecrecoverWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public pure returns (bytes32 orderHash) { if(signType == 1 ) { orderHash = keccak256(abi.encodePacked(token, amount, to, nonce,feeToken,feeWithdrawal,timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != from) { revert(ECRECOVER_FAILED); } } else { orderHash = keccak256(abi.encode(WITHDRAW_TYPEHASH,token, amount, to, nonce,feeToken,feeWithdrawal,timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)), v, rs[0], rs[1]) != from) { revert(ECRECOVER_FAILED); } } } /** * @dev burn the stored gastoken * @param gasUsed The gas uesed to calc the gastoken to burn */ function _burnGas(uint gasUsed) internal { if(_gasStorage == address(0x0)){ return; } IGasStorage(_gasStorage).burn(gasUsed); } }
Airdrop the token directly to Dex user's walle,only airdrop contract can call this function. to the recipient token the ERC20 token to send amount the token amount to send/Not EOA
function airdrop(address to,address token,uint256 amount) public onlyAirdropContract { require(tx.origin != msg.sender); require(_balances[token][msg.sender] >= amount ,INSUFFICIENT_FOUND); _balances[token][msg.sender] = _balances[token][msg.sender].sub(amount); _balances[token][to] = _balances[token][to].add(amount); emit Airdrop(to,token,amount); }
1,805,340
pragma solidity 0.7.6; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import "./interfaces/IArbitrator.sol"; import "./interfaces/IArbitrable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Arbitrator is IArbitrator, Ownable { event DisputeStateChanged(uint256 indexed disputeId, DisputeState indexed state); event EvidenceSubmitted(uint256 indexed disputeId, address indexed submitter, bytes evidence); event EvidencePeriodClosed(uint256 indexed disputeId, uint64 indexed termId); event NewDispute(uint256 indexed disputeId, IArbitrable indexed subject, bytes metadata); event RulingComputed(uint256 indexed disputeId, uint8 indexed ruling); enum DisputeState { PreDraft, Adjudicating, Ruled } struct Dispute { IArbitrable subject; // Arbitrable associated to a dispute uint8 possibleRulings; // Number of possible rulings jurors can vote for each dispute uint8 finalRuling; // Winning ruling of a dispute DisputeState state; // State of a dispute: pre-draft, adjudicating, or ruled } Dispute[] internal disputes; /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return disputeId Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes memory _metadata) external override returns (uint256 disputeId) { require(_possibleRulings == 1, "ERROR_INVALID_RULING_OPTIONS"); // Create the dispute disputeId = disputes.length; Dispute storage dispute = disputes[disputeId]; dispute.subject = IArbitrable(msg.sender); dispute.possibleRulings = uint8(_possibleRulings); emit NewDispute(disputeId, IArbitrable(msg.sender), _metadata); } /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Protocol * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes memory _evidence) external override { Dispute storage dispute = disputes[_disputeId]; require(dispute.subject == IArbitrable(msg.sender), "ERROR_SUBJECT_NOT_DISPUTE_SUBJECT"); emit EvidenceSubmitted(_disputeId, _submitter, _evidence); } /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external override { Dispute storage dispute = disputes[_disputeId]; require(dispute.subject == IArbitrable(msg.sender), "ERROR_SUBJECT_NOT_DISPUTE_SUBJECT"); emit EvidencePeriodClosed(_disputeId, 0); } /** * @notice Rule dispute #`_disputeId` to ruling number `_ruling` * @param _disputeId Identification number of the dispute to be ruled * @param _ruling Ruling number of the given dispute */ function setRuling(uint256 _disputeId, uint8 _ruling) onlyOwner external { Dispute storage dispute = disputes[_disputeId]; require (dispute.state != DisputeState.Ruled, "ERROR_DISPUTE_ALREADY_RULED"); require (_ruling != 0, "ERROR_INVALID_RULING"); dispute.finalRuling = _ruling; dispute.state = DisputeState.Ruled; emit RulingComputed(_disputeId, dispute.finalRuling); } /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Arbitrable instance associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external override view returns (address subject, uint256 ruling) { Dispute storage dispute = disputes[_disputeId]; subject = address(dispute.subject); ruling = dispute.finalRuling; } /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external override pure returns (address recipient, ERC20 feeToken, uint256 feeAmount) { return (address(0), ERC20(0), 0); } /** * @dev Tell the subscription fees information for a subscriber to be up-to-date * @return recipient Address where the corresponding subscriptions fees must be transferred to * @return feeToken ERC20 token used for the subscription fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getSubscriptionFees(address /*_subscriber*/) external override pure returns (address recipient, ERC20 feeToken, uint256 feeAmount) { return (address(0), ERC20(0), 0); } }
Close the evidence period of a dispute _disputeId Identification number of the dispute to close its evidence submitting period/
function closeEvidencePeriod(uint256 _disputeId) external override { Dispute storage dispute = disputes[_disputeId]; require(dispute.subject == IArbitrable(msg.sender), "ERROR_SUBJECT_NOT_DISPUTE_SUBJECT"); emit EvidencePeriodClosed(_disputeId, 0); }
13,031,805
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./IGage.sol"; /** * @dev Loyalty Gage interface * @author Nobody (me) * @notice Methods are used for all loyalty gage contracts */ interface ILoyaltyGage is IGage { // Initializes the loyalty gage function initialize(address rAsset, address dAsset, uint256 rAmount, uint256 dAmount, uint256 rRisk, uint256 dRisk) external; // View the distributor of the loyalty gage (usually token distributor) function viewDistributor() external view returns (address); // View the receiver in the loyalty gage (usually the user) function viewReceiver() external view returns (address); // View the gage's percent change in supply condition function viewPercent() external view returns (uint256); // View the whether the gage's deposit is inflationary or deflationary function viewInflationary() external view returns (bool); }
Loyalty Gage interface Nobody (me) Methods are used for all loyalty gage contracts/ Initializes the loyalty gage View the distributor of the loyalty gage (usually token distributor) View the receiver in the loyalty gage (usually the user) View the gage's percent change in supply condition View the whether the gage's deposit is inflationary or deflationary
interface ILoyaltyGage is IGage { function initialize(address rAsset, address dAsset, uint256 rAmount, uint256 dAmount, uint256 rRisk, uint256 dRisk) external; function viewDistributor() external view returns (address); function viewReceiver() external view returns (address); function viewPercent() external view returns (uint256); function viewInflationary() external view returns (bool); pragma solidity 0.8.0; }
12,796,523
// hevm: flattened sources of src/pickle-jar.sol pragma solidity >=0.6.0 <0.7.0; ////// src/interfaces/controller.sol // SPDX-License-Identifier: MIT /* pragma solidity ^0.6.0; */ interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } ////// src/lib/context.sol // SPDX-License-Identifier: MIT /* pragma solidity ^0.6.0; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } ////// src/lib/safe-math.sol // SPDX-License-Identifier: MIT /* pragma solidity ^0.6.0; */ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath_2 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } ////// src/lib/erc20.sol // File: contracts/GSN/Context.sol // SPDX-License-Identifier: MIT /* pragma solidity ^0.6.0; */ /* import "./safe-math.sol"; */ /* import "./context.sol"; */ // File: contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20_2 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address_2 { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20_2 { using SafeMath_2 for uint256; using Address_2 for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20_2 { using SafeMath_2 for uint256; using Address_2 for address; function safeTransfer(IERC20_2 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20_2 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_2 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_2 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_2 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_2 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"); } } } ////// src/pickle-jar.sol // https://github.com/iearn-finance/vaults/blob/master/contracts/vaults/yVault.sol /* pragma solidity ^0.6.7; */ /* import "./interfaces/controller.sol"; */ /* import "./lib/erc20.sol"; */ /* import "./lib/safe-math.sol"; */ contract PickleJar is ERC20 { using SafeERC20_2 for IERC20_2; using Address_2 for address; using SafeMath_2 for uint256; IERC20_2 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public timelock; address public controller; constructor(address _token, address _governance, address _timelock, address _controller) public ERC20( string(abi.encodePacked("pickling ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20_2(_token); governance = _governance; timelock = _timelock; controller = _controller; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); require(_min <= max, "numerator cannot be greater than denominator"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) public { require(msg.sender == timelock, "!timelock"); controller = _controller; } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20_2(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } }
Interface of the ERC20 standard as defined in the EIP./
interface IERC20_2 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
571,868
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/truefi/ITrueFiPool.sol pragma solidity 0.6.10; /** * TrueFiPool is an ERC20 which represents a share of a pool * * This contract can be used to wrap opportunities to be compatible * with TrueFi and allow users to directly opt-in through the TUSD contract * * Each TrueFiPool is also a staking opportunity for TRU */ interface ITrueFiPool is IERC20 { /** * @dev join pool * 1. Transfer TUSD from sender * 2. Mint pool tokens based on value to sender */ function join(uint256 amount) external; /** * @dev exit pool * 1. Transfer pool tokens from sender * 2. Burn pool tokens * 3. Transfer value of pool tokens in TUSD to sender */ function exit(uint256 amount) external; /// @dev get token value for pool token function value() external view returns (uint256); /// @dev stake TRU function stake(uint256 amount) external; /// @dev unstake TRU function unstake(uint256 amount) external; } // File: contracts/truefi/TrueFiPool.sol pragma solidity 0.6.10; /** * TrueFiPool is an ERC20 which represents a share of a pool. * * This contract can be used to wrap opportunities to be compatible * with TrueFi and allow users to directly opt-in through the TUSD contract * * Each TrueFiPool is also a staking opportunity for TRU */ abstract contract TrueFiPool is ITrueFiPool, ERC20 { IERC20 public token; constructor( IERC20 _token, string memory name, string memory symbol ) public ERC20(name, symbol) { token = _token; } /// @dev only TrueFi smart contract modifier onlyTrueFi() { _; } /// @dev update paramaters function update(bytes32 params) external onlyTrueFi { // TODO // do we need this function, or do updates happen via proxy upgrades? } /** * @dev join pool * 1. Transfer TUSD from sender * 2. Exchange TUSD for pool tokens */ function join(uint256 amount) external virtual override { // TODO } /** * @dev exit pool * 1. Transfer pool tokens from sender * 2. Exchange pool tokens for TUSD * 3. Burn pool tokens */ function exit(uint256 amount) external virtual override { // TODO } /// @dev get token value for pool token function value() external virtual override view returns (uint256) { // TODO return 0; } /// @dev stake TRU function stake(uint256 amount) external override { // TODO } /// @dev unstake TRU function unstake(uint256 amount) external override { // TODO } } // File: contracts/truefi/ICurvePool.sol pragma solidity 0.6.10; interface ICurve { function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256); } interface ICurvePool { function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, uint128 i, uint256 min_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function token() external view returns (IERC20); function curve() external view returns (ICurve); } // File: contracts/truefi/CurvePool.sol pragma solidity 0.6.10; contract CurvePool is TrueFiPool { ICurvePool public curvePool; uint8 constant N_TOKENS = 4; uint8 constant TUSD_INDEX = 3; constructor(ICurvePool _curve, IERC20 token) public TrueFiPool(token, "CurveTUSDPool", "CurTUSD") { curvePool = _curve; token.approve(address(curvePool), uint256(-1)); curvePool.token().approve(address(curvePool), uint256(-1)); } function join(uint256 amount) external override { require(token.transferFrom(msg.sender, address(this), amount)); uint256[N_TOKENS] memory amounts = [0, 0, 0, amount]; uint256 minTokenAmount = curvePool.curve().calc_token_amount(amounts, true).mul(99).div(100); uint256 balanceBefore = curvePool.token().balanceOf(address(this)); curvePool.add_liquidity(amounts, minTokenAmount); uint256 balanceAfter = curvePool.token().balanceOf(address(this)); _mint(msg.sender, balanceAfter.sub(balanceBefore)); } function exit(uint256 amount) external override { require(amount <= balanceOf(msg.sender), "Insufficient balance"); uint256 minTokenAmount = curvePool.calc_withdraw_one_coin(amount, TUSD_INDEX).mul(99).div(100); uint256 balanceBefore = token.balanceOf(address(this)); curvePool.remove_liquidity_one_coin(amount, TUSD_INDEX, minTokenAmount); uint256 balanceAfter = token.balanceOf(address(this)); require(token.transfer(msg.sender, balanceAfter.sub(balanceBefore))); _burn(msg.sender, amount); } function value() external override view returns (uint256) { return curvePool.calc_withdraw_one_coin(1 ether, TUSD_INDEX); } }
update paramaters TODO do we need this function, or do updates happen via proxy upgrades?
function update(bytes32 params) external onlyTrueFi { }
1,198,917
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./interface/IVBNB.sol"; import "./interface/CompleteVToken.sol"; import "../../lib/@harvest-finance/hardworkInterface/IStrategy.sol"; import "./interface/WBNB.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract VenusInteractorInitializable is Initializable, ReentrancyGuardUpgradeable { using SafeMath for uint256; using SafeBEP20 for IBEP20; IBEP20 public underlyingToken; address payable public _wbnb; CompleteVToken public vtoken; ComptrollerInterface public comptroller; constructor() public { } function initialize( address _underlying, address _vtoken, address _comptroller ) public initializer { __ReentrancyGuard_init(); // Comptroller: comptroller = ComptrollerInterface(_comptroller); underlyingToken = IBEP20(_underlying); _wbnb = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; vtoken = CompleteVToken(_vtoken); // Enter the market address[] memory vTokens = new address[](1); vTokens[0] = _vtoken; comptroller.enterMarkets(vTokens); } /** * Supplies BNB to Venus * Unwraps WBNB to BNB, then invoke the special mint for vBNB * We ask to supply "amount", if the "amount" we asked to supply is * more than balance (what we really have), then only supply balance. * If we the "amount" we want to supply is less than balance, then * only supply that amount. */ function _supplyBNBInWBNB(uint256 amountInWBNB) internal nonReentrant { // underlyingToken here is WBNB uint256 balance = underlyingToken.balanceOf(address(this)); // supply at most "balance" if (amountInWBNB < balance) { balance = amountInWBNB; // only supply the "amount" if its less than what we have } WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.withdraw(balance); // Unwrapping IVBNB(address(vtoken)).mint.value(balance)(); } /** * Redeems BNB from Venus * receives BNB. Wrap all the BNB that is in this contract. */ function _redeemBNBInvTokens(uint256 amountVTokens) internal nonReentrant { _redeemInVTokens(amountVTokens); WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.deposit.value(address(this).balance)(); } /** * Supplies to Venus */ function _supply(uint256 amount) internal returns(uint256) { uint256 balance = underlyingToken.balanceOf(address(this)); if (amount < balance) { balance = amount; } underlyingToken.safeApprove(address(vtoken), 0); underlyingToken.safeApprove(address(vtoken), balance); uint256 mintResult = vtoken.mint(balance); require(mintResult == 0, "Supplying failed"); return balance; } /** * Borrows against the collateral */ function _borrow(uint256 amountUnderlying) internal { // Borrow, check the balance for this contract's address uint256 result = vtoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); } /** * Borrows against the collateral */ function _borrowInWBNB(uint256 amountUnderlying) internal { // Borrow BNB, wraps into WBNB uint256 result = vtoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.deposit.value(address(this).balance)(); } /** * Repays a loan */ function _repay(uint256 amountUnderlying) internal { underlyingToken.safeApprove(address(vtoken), 0); underlyingToken.safeApprove(address(vtoken), amountUnderlying); vtoken.repayBorrow(amountUnderlying); underlyingToken.safeApprove(address(vtoken), 0); } /** * Repays a loan in BNB */ function _repayInWBNB(uint256 amountUnderlying) internal { WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.withdraw(amountUnderlying); // Unwrapping IVBNB(address(vtoken)).repayBorrow.value(amountUnderlying)(); } /** * Redeem liquidity in vTokens */ function _redeemInVTokens(uint256 amountVTokens) internal { if(amountVTokens > 0){ vtoken.redeem(amountVTokens); } } /** * Redeem liquidity in underlying */ function _redeemUnderlying(uint256 amountUnderlying) internal { if (amountUnderlying > 0) { vtoken.redeemUnderlying(amountUnderlying); } } /** * Redeem liquidity in underlying */ function redeemUnderlyingInWBNB(uint256 amountUnderlying) internal { if (amountUnderlying > 0) { _redeemUnderlying(amountUnderlying); WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.deposit.value(address(this).balance)(); } } /** * Get XVS */ function claimVenus() public { comptroller.claimVenus(address(this)); } /** * Redeem the minimum of the WBNB we own, and the WBNB that the vToken can * immediately retrieve. Ensures that `redeemMaximum` doesn't fail silently */ function redeemMaximumWBNB() internal { // amount of WBNB in contract uint256 available = vtoken.getCash(); // amount of WBNB we own uint256 owned = vtoken.balanceOfUnderlying(address(this)); // redeem the most we can redeem redeemUnderlyingInWBNB(available < owned ? available : owned); } function redeemMaximumWithLoan(uint256 collateralFactorNumerator, uint256 collateralFactorDenominator, uint256 borrowMinThreshold) internal { // amount of liquidity in Venus uint256 available = vtoken.getCash(); // amount we supplied uint256 supplied = vtoken.balanceOfUnderlying(address(this)); // amount we borrowed uint256 borrowed = vtoken.borrowBalanceCurrent(address(this)); while (borrowed > borrowMinThreshold) { uint256 requiredCollateral = borrowed .mul(collateralFactorDenominator) .add(collateralFactorNumerator.div(2)) .div(collateralFactorNumerator); // redeem just as much as needed to repay the loan uint256 wantToRedeem = supplied.sub(requiredCollateral); _redeemUnderlying(SafeMath.min(wantToRedeem, available)); // now we can repay our borrowed amount uint256 balance = underlyingToken.balanceOf(address(this)); _repay(SafeMath.min(borrowed, balance)); // update the parameters available = vtoken.getCash(); borrowed = vtoken.borrowBalanceCurrent(address(this)); supplied = vtoken.balanceOfUnderlying(address(this)); } // redeem the most we can redeem _redeemUnderlying(SafeMath.min(available, supplied)); } function redeemMaximumWBNBWithLoan(uint256 collateralFactorNumerator, uint256 collateralFactorDenominator, uint256 borrowMinThreshold) internal { // amount of liquidity in Venus uint256 available = vtoken.getCash(); // amount of WBNB we supplied uint256 supplied = vtoken.balanceOfUnderlying(address(this)); // amount of WBNB we borrowed uint256 borrowed = vtoken.borrowBalanceCurrent(address(this)); while (borrowed > borrowMinThreshold) { uint256 requiredCollateral = borrowed .mul(collateralFactorDenominator) .add(collateralFactorNumerator.div(2)) .div(collateralFactorNumerator); // redeem just as much as needed to repay the loan uint256 wantToRedeem = supplied.sub(requiredCollateral); redeemUnderlyingInWBNB(SafeMath.min(wantToRedeem, available)); // now we can repay our borrowed amount uint256 balance = underlyingToken.balanceOf(address(this)); _repayInWBNB(SafeMath.min(borrowed, balance)); // update the parameters available = vtoken.getCash(); borrowed = vtoken.borrowBalanceCurrent(address(this)); supplied = vtoken.balanceOfUnderlying(address(this)); } // redeem the most we can redeem redeemUnderlyingInWBNB(SafeMath.min(available, supplied)); } function getLiquidity() external view returns(uint256) { return vtoken.getCash(); } function redeemMaximumToken() internal { // amount of tokens in vtoken uint256 available = vtoken.getCash(); // amount of tokens we own uint256 owned = vtoken.balanceOfUnderlying(address(this)); // redeem the most we can redeem _redeemUnderlying(available < owned ? available : owned); } receive() external payable {} // this is needed for the WBNB unwrapping }
Redeems BNB from Venus receives BNB. Wrap all the BNB that is in this contract./
function _redeemBNBInvTokens(uint256 amountVTokens) internal nonReentrant { _redeemInVTokens(amountVTokens); WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.deposit.value(address(this).balance)(); }
1,037,902
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {MintableBurnableERC20} from './MintableBurnableERC20.sol'; import {Lockable} from '@uma/core/contracts/common/implementation/Lockable.sol'; /** * @title Synthetic token contract * Inherits from MintableBurnableERC20 */ contract MintableBurnableSyntheticToken is MintableBurnableERC20, Lockable { constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) MintableBurnableERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add minter role to account * @dev The caller must have the admin role * @param account The address on which minter role is added */ function addMinter(address account) public override nonReentrant() { super.addMinter(account); } /** * @notice Add burner role to account * @dev The caller must have the admin role * @param account The address to which burner role is added */ function addBurner(address account) public override nonReentrant() { super.addBurner(account); } /** * @notice Add admin role to account. * @dev The caller must have the admin role. * @param account The address to which the admin role is added. */ function addAdmin(address account) public override nonReentrant() { super.addAdmin(account); } /** * @notice Add admin, minter and burner roles to account. * @dev The caller must have the admin role. * @param account The address to which the admin, minter and burner roles are added. */ function addAdminAndMinterAndBurner(address account) public override nonReentrant() { super.addAdminAndMinterAndBurner(account); } /** * @notice Minter renounce to minter role */ function renounceMinter() public override nonReentrant() { super.renounceMinter(); } /** * @notice Burner renounce to burner role */ function renounceBurner() public override nonReentrant() { super.renounceBurner(); } /** * @notice Admin renounce to admin role */ function renounceAdmin() public override nonReentrant() { super.renounceAdmin(); } /** * @notice Admin, minter and murner renounce to admin, minter and burner roles */ function renounceAdminAndMinterAndBurner() public override nonReentrant() { super.renounceAdminAndMinterAndBurner(); } /** * @notice Checks if a given account holds the minter role. * @param account The address which is checked for the minter role. * @return bool True if the provided account is a minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return hasRole(MINTER_ROLE, account); } /** * @notice Checks if a given account holds the burner role. * @param account The address which is checked for the burner role. * @return bool True if the provided account is a burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return hasRole(BURNER_ROLE, account); } /** * @notice Checks if a given account holds the admin role. * @param account The address which is checked for the admin role. * @return bool True if the provided account is an admin. */ function isAdmin(address account) public view nonReentrantView() returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, account); } /** * @notice Accessor method for the list of member with admin role * @return array of address with admin role */ function getAdminMembers() external view returns (address[] memory) { uint256 numberOfMembers = getRoleMemberCount(DEFAULT_ADMIN_ROLE); address[] memory members = new address[](numberOfMembers); for (uint256 j = 0; j < numberOfMembers; j++) { address newMember = getRoleMember(DEFAULT_ADMIN_ROLE, j); members[j] = newMember; } return members; } /** * @notice Accessor method for the list of member with minter role * @return array of address with minter role */ function getMinterMembers() external view returns (address[] memory) { uint256 numberOfMembers = getRoleMemberCount(MINTER_ROLE); address[] memory members = new address[](numberOfMembers); for (uint256 j = 0; j < numberOfMembers; j++) { address newMember = getRoleMember(MINTER_ROLE, j); members[j] = newMember; } return members; } /** * @notice Accessor method for the list of member with burner role * @return array of address with burner role */ function getBurnerMembers() external view returns (address[] memory) { uint256 numberOfMembers = getRoleMemberCount(BURNER_ROLE); address[] memory members = new address[](numberOfMembers); for (uint256 j = 0; j < numberOfMembers; j++) { address newMember = getRoleMember(BURNER_ROLE, j); members[j] = newMember; } return members; } }
Admin, minter and murner renounce to admin, minter and burner roles/
function renounceAdminAndMinterAndBurner() public override nonReentrant() { super.renounceAdminAndMinterAndBurner(); }
15,814,595
pragma solidity 0.5.10; /// @dev Randomness test contract based on https://github.com/poanetwork/posdao-contracts. /// Generates and stores random numbers in a RANDAO manner and accumulates a random seed. contract Random { mapping(uint256 => mapping(address => bytes32)) public hashes; mapping(uint256 => mapping(address => bytes)) public ciphers; mapping(uint256 => mapping(address => uint256)) public secrets; uint256 public value; /// @dev Called by the validator's node to store a hash and a cipher of the validator's secret on each collection /// round. The validator's node must use its mining address to call this function. /// This function can only be called once per collection round (during the `commits phase`). /// @param _secretHash The Keccak-256 hash of the validator's secret. /// @param _cipher The cipher of the validator's secret. Can be used by the node to decrypt and reveal. function commitHash(bytes32 _secretHash, bytes calldata _cipher) external { require(block.coinbase == msg.sender); require(_isCommitPhase(block.number - 1)); uint256 round = _collectRound(block.number - 1); require(!isCommitted(round, msg.sender)); hashes[round][msg.sender] = _secretHash; ciphers[round][msg.sender] = _cipher; } /// @dev Called by the validator's node to XOR its secret with the current random seed. /// The validator's node must use its mining address to call this function. /// This function can only be called once per collection round (during the `reveals phase`). /// @param _number The validator's secret. function revealNumber(uint256 _number) external { require(block.coinbase == msg.sender); require(_isRevealPhase(block.number - 1)); uint256 round = _collectRound(block.number - 1); require(!sentReveal(round, msg.sender)); require(hashes[round][msg.sender] == keccak256(abi.encodePacked(_number))); secrets[round][msg.sender] = _number; value ^= _number; } /// @dev Returns the Keccak-256 hash and cipher of the validator's secret for the specified collection round /// and the specified validator stored by the validator through the `commitHash` function. /// @param _collectRound The serial number of the collection round for which hash and cipher should be retrieved. /// @param _miningAddress The mining address of validator. function getCommitAndCipher( uint256 _collectRound, address _miningAddress ) public view returns(bytes32, bytes memory) { return (hashes[_collectRound][_miningAddress], ciphers[_collectRound][_miningAddress]); } /// @dev Returns a boolean flag indicating whether the specified validator has committed their secret's hash for the /// specified collection round. /// @param _collectRound The serial number of the collection round for which the checkup should be done. /// @param _miningAddress The mining address of the validator. function isCommitted(uint256 _collectRound, address _miningAddress) public view returns(bool) { return hashes[_collectRound][_miningAddress] != bytes32(0); } /// @dev Returns a boolean flag indicating whether the current phase of the current collection round /// is a `commits phase`. Used by the validator's node to determine if it should commit the hash of /// the secret during the current collection round. function isCommitPhase() public view returns(bool) { return _isCommitPhase(block.number); } /// @dev Returns a boolean flag indicating whether the current phase of the current collection round /// is a `reveals phase`. Used by the validator's node to determine if it should reveal the secret during /// the current collection round. function isRevealPhase() public view returns(bool) { return _isRevealPhase(block.number); } /// @dev Returns a boolean flag of whether the specified validator has revealed their secret for the /// specified collection round. /// @param _collectRound The serial number of the collection round for which the checkup should be done. /// @param _miningAddress The mining address of the validator. function sentReveal(uint256 _collectRound, address _miningAddress) public view returns(bool) { return secrets[_collectRound][_miningAddress] != uint256(0); } /// @dev Returns the current collect round number. function currentCollectRound() public view returns(uint256) { return _collectRound(block.number); } /// @dev Returns the current random value. function getValue() public view returns(uint256) { return value; } function _collectRound(uint256 blockNumber) private pure returns(uint256) { return blockNumber / 6; } function _isCommitPhase(uint256 blockNumber) private pure returns(bool) { return blockNumber % 6 < 3; } function _isRevealPhase(uint256 blockNumber) private pure returns(bool) { return blockNumber % 6 >= 3; } }
Returns the Keccak-256 hash and cipher of the validator's secret for the specified collection round and the specified validator stored by the validator through the `commitHash` function. _collectRound The serial number of the collection round for which hash and cipher should be retrieved. _miningAddress The mining address of validator.
function getCommitAndCipher( uint256 _collectRound, address _miningAddress ) public view returns(bytes32, bytes memory) { return (hashes[_collectRound][_miningAddress], ciphers[_collectRound][_miningAddress]); }
7,296,754
pragma solidity ^0.4.22; /** * @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 a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract EstateParticipationUnit { using SafeMath for uint256; enum VoteType { NONE, ALLOW_TRANSFER, CHANGE_ADMIN_WALLET, CHANGE_BUY_SELL_LIMITS, CHANGE_BUY_SELL_PRICE, SEND_WEI_FROM_EXCHANGE, SEND_WEI_FROM_PAYMENT, TRANSFER_EXCHANGE_WEI_TO_PAYMENT, START_PAYMENT } struct VoteData { bool voteYes; bool voteCancel; address person; uint lastVoteId; } struct PaymentData { uint weiTotal; uint weiReceived; uint unitsTotal; uint unitsReceived; uint weiForSingleUnit; } struct BalanceData { uint balance; uint transferAllowed; uint balancePaymentSeries; VoteData vote; mapping (address => uint) allowed; bytes32 paymentBalances; } struct ChangeBuySellPriceVoteData { bool ignoreSecurityLimits; uint buyPrice; uint buyAddUnits; uint sellPrice; uint sellAddUnits; } struct AllowTransferVoteData { address addressTo; uint amount; } struct ChangeAdminAddressVoteData { uint index; address adminAddress; } struct ChangeBuySellLimitsVoteData { uint buyPriceMin; uint buyPriceMax; uint sellPriceMin; uint sellPriceMax; } struct SendWeiFromExchangeVoteData { address addressTo; uint amount; } struct SendWeiFromPaymentVoteData { address addressTo; uint amount; } struct TransferWeiFromExchangeToPaymentVoteData { bool reverse; uint amount; } struct StartPaymentVoteData { uint weiToShare; uint date; } struct PriceSumData { uint price; uint amount; } modifier onlyAdmin() { require (isAdmin(msg.sender)); _; } address private mainBalanceAdmin; address private buyBalanceAdmin; address private sellBalanceAdmin; string public constant name = "Estate Participation Unit"; string public constant symbol = "EPU"; uint8 public constant decimals = 0; uint public amountOfUnitsOutsideAdminWallet = 0; uint private constant maxUnits = 200000000; uint public paymentNumber = 0; uint public paymentSortId = 0; uint private paymentSeries = 0; bytes32 private paymentHistory; uint public weiForPayment = 0; uint public totalAmountOfWeiPaidToUsers = 0; uint private totalAmountOfWeiPaidToUsersPerSeries = 0; uint private totalAmountOfWeiOnPaymentsPerSeries = 0; uint public lastPaymentDate; uint private weiBuyPrice = 50000000000000000; uint private securityWeiBuyPriceFrom = 0; uint private securityWeiBuyPriceTo = 0; uint private weiSellPrice = 47000000000000000; uint public unitsToSell = 0; uint private securityWeiSellPriceFrom = 0; uint private securityWeiSellPriceTo = 0; uint public weiFromExchange = 0; PriceSumData private buySum; PriceSumData private sellSum; uint private voteId = 0; bool private voteInProgress; uint private votesTotalYes; uint private votesTotalNo; uint private voteCancel; AllowTransferVoteData private allowTransferVoteData; ChangeAdminAddressVoteData private changeAdminAddressVoteData; ChangeBuySellLimitsVoteData private changeBuySellLimitsVoteData; ChangeBuySellPriceVoteData private changeBuySellPriceVoteData; SendWeiFromExchangeVoteData private sendWeiFromExchangeVoteData; SendWeiFromPaymentVoteData private sendWeiFromPaymentVoteData; TransferWeiFromExchangeToPaymentVoteData private transferWeiFromExchangeToPaymentVoteData; StartPaymentVoteData private startPaymentVoteData; VoteType private voteType = VoteType.NONE; mapping(address => BalanceData) private balances; event Transfer(address indexed from, address indexed to, uint units); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event OnEmitNewUnitsFromMainWallet(uint units, uint totalOutside); event OnAddNewUnitsToMainWallet(uint units, uint totalOutside); event NewPayment(uint indexed index, uint totalWei, uint totalUnits, uint date); event PaymentReceived(address indexed owner, uint paymentId, uint weiAmount, uint units); event UnitsBuy(address indexed buyer, uint amount); event UnitsSell(address indexed seller, uint amount); event OnExchangeBuyUpdate(uint newValue, uint unitsToBuy); event OnExchangeSellUpdate(uint newValue, uint unitsToSell); modifier startVoting { require(voteType == VoteType.NONE); _; } constructor( uint paymentOffset, address mainBalanceAdminAddress, address buyBalanceAdminAddress, address sellBalanceAdminAddress ) payable public { paymentNumber = paymentOffset; mainBalanceAdmin = mainBalanceAdminAddress; buyBalanceAdmin = buyBalanceAdminAddress; sellBalanceAdmin = sellBalanceAdminAddress; BalanceData storage b = balances[mainBalanceAdminAddress]; b.balance = maxUnits; weiForPayment = weiForPayment.add(msg.value); } function getAdminAccounts() external onlyAdmin view returns( address mainBalanceAdminAddress, address buyBalanceAdminAddress, address sellBalanceAdminAddress ) { mainBalanceAdminAddress = mainBalanceAdmin; buyBalanceAdminAddress = buyBalanceAdmin; sellBalanceAdminAddress = sellBalanceAdmin; } function getBuySellSum() external onlyAdmin view returns( uint buyPrice, uint buyAmount, uint sellPrice, uint sellAmount ) { buyPrice = buySum.price; buyAmount = buySum.amount; sellPrice = sellSum.price; sellAmount = sellSum.amount; } function getSecurityLimits() external view returns( uint buyPriceFrom, uint buyPriceTo, uint sellPriceFrom, uint sellPriceTo ) { buyPriceFrom = securityWeiBuyPriceFrom; buyPriceTo = securityWeiBuyPriceTo; sellPriceFrom = securityWeiSellPriceFrom; sellPriceTo = securityWeiSellPriceTo; } function getThisAddress() external view returns (address) { return address(this); } function() payable external { weiForPayment = weiForPayment.add(msg.value); } function startVotingForAllowTransfer( address addressTo, uint amount ) external onlyAdmin startVoting { voteType = VoteType.ALLOW_TRANSFER; allowTransferVoteData.addressTo = addressTo; allowTransferVoteData.amount = amount; internalStartVoting(); } function startVotingForChangeAdminAddress( uint index, address adminAddress ) external onlyAdmin startVoting { require(!isAdmin(adminAddress)); voteType = VoteType.CHANGE_ADMIN_WALLET; changeAdminAddressVoteData.index = index; changeAdminAddressVoteData.adminAddress = adminAddress; internalStartVoting(); } function startVotingForChangeBuySellLimits( uint buyPriceMin, uint buyPriceMax, uint sellPriceMin, uint sellPriceMax ) external onlyAdmin startVoting { if(buyPriceMin > 0 && buyPriceMax > 0) { require(buyPriceMin < buyPriceMax); } if(sellPriceMin > 0 && sellPriceMax > 0) { require(sellPriceMin < sellPriceMax); } if(buyPriceMin > 0 && sellPriceMax > 0) { require(buyPriceMin >= sellPriceMax); } voteType = VoteType.CHANGE_BUY_SELL_LIMITS; changeBuySellLimitsVoteData.buyPriceMin = buyPriceMin; changeBuySellLimitsVoteData.buyPriceMax = buyPriceMax; changeBuySellLimitsVoteData.sellPriceMin = sellPriceMin; changeBuySellLimitsVoteData.sellPriceMax = sellPriceMax; internalStartVoting(); } function startVotingForChangeBuySellPrice( uint buyPrice, uint buyAddUnits, uint sellPrice, uint sellAddUnits, bool ignoreSecurityLimits ) external onlyAdmin startVoting { require(buyPrice >= sellPrice); require(sellAddUnits * sellPrice <= weiFromExchange); voteType = VoteType.CHANGE_BUY_SELL_PRICE; changeBuySellPriceVoteData.buyPrice = buyPrice; changeBuySellPriceVoteData.buyAddUnits = buyAddUnits; changeBuySellPriceVoteData.sellPrice = sellPrice; changeBuySellPriceVoteData.sellAddUnits = sellAddUnits; changeBuySellPriceVoteData.ignoreSecurityLimits = ignoreSecurityLimits; internalStartVoting(); } function startVotingForSendWeiFromExchange( address addressTo, uint amount ) external onlyAdmin startVoting { require(amount <= weiFromExchange); voteType = VoteType.SEND_WEI_FROM_EXCHANGE; sendWeiFromExchangeVoteData.addressTo = addressTo; sendWeiFromExchangeVoteData.amount = amount; internalStartVoting(); } function startVotingForSendWeiFromPayment( address addressTo, uint amount ) external onlyAdmin startVoting { uint balance = address(this).balance.sub(weiFromExchange); require(amount <= balance && amount <= weiForPayment); voteType = VoteType.SEND_WEI_FROM_PAYMENT; sendWeiFromPaymentVoteData.addressTo = addressTo; sendWeiFromPaymentVoteData.amount = amount; internalStartVoting(); } function startVotingForTransferWeiFromExchangeToPayment( bool reverse, uint amount ) external onlyAdmin startVoting { if(reverse) { require(amount <= weiForPayment); } else { require(amount <= weiFromExchange); } voteType = VoteType.TRANSFER_EXCHANGE_WEI_TO_PAYMENT; transferWeiFromExchangeToPaymentVoteData.reverse = reverse; transferWeiFromExchangeToPaymentVoteData.amount = amount; internalStartVoting(); } function startVotingForStartPayment( uint weiToShare, uint date ) external onlyAdmin startVoting { require(weiToShare > 0 && weiToShare <= weiForPayment); voteType = VoteType.START_PAYMENT; startPaymentVoteData.weiToShare = weiToShare; startPaymentVoteData.date = date; internalStartVoting(); } function voteForCurrent(bool voteYes) external onlyAdmin { require(voteType != VoteType.NONE); VoteData storage d = balances[msg.sender].vote; // already voted if(d.lastVoteId == voteId) { // ...but changed mind if(voteYes != d.voteYes) { if(voteYes) { votesTotalYes = votesTotalYes.add(1); votesTotalNo = votesTotalNo.sub(1); } else { votesTotalYes = votesTotalYes.sub(1); votesTotalNo = votesTotalNo.add(1); } } } // a new vote // adding 'else' costs more gas if(d.lastVoteId < voteId) { if(voteYes) { votesTotalYes = votesTotalYes.add(1); } else { votesTotalNo = votesTotalNo.add(1); } } // 5 / 10 means something is voted out if(votesTotalYes.mul(10).div(3) > 5) { // adding 'else' for each vote type costs more gas if(voteType == VoteType.ALLOW_TRANSFER) { internalAllowTransfer( allowTransferVoteData.addressTo, allowTransferVoteData.amount ); } if(voteType == VoteType.CHANGE_ADMIN_WALLET) { internalChangeAdminWallet( changeAdminAddressVoteData.index, changeAdminAddressVoteData.adminAddress ); } if(voteType == VoteType.CHANGE_BUY_SELL_LIMITS) { internalChangeBuySellLimits( changeBuySellLimitsVoteData.buyPriceMin, changeBuySellLimitsVoteData.buyPriceMax, changeBuySellLimitsVoteData.sellPriceMin, changeBuySellLimitsVoteData.sellPriceMax ); } if(voteType == VoteType.CHANGE_BUY_SELL_PRICE) { internalChangeBuySellPrice( changeBuySellPriceVoteData.buyPrice, changeBuySellPriceVoteData.buyAddUnits, changeBuySellPriceVoteData.sellPrice, changeBuySellPriceVoteData.sellAddUnits, changeBuySellPriceVoteData.ignoreSecurityLimits ); } if(voteType == VoteType.SEND_WEI_FROM_EXCHANGE) { internalSendWeiFromExchange( sendWeiFromExchangeVoteData.addressTo, sendWeiFromExchangeVoteData.amount ); } if(voteType == VoteType.SEND_WEI_FROM_PAYMENT) { internalSendWeiFromPayment( sendWeiFromPaymentVoteData.addressTo, sendWeiFromPaymentVoteData.amount ); } if(voteType == VoteType.TRANSFER_EXCHANGE_WEI_TO_PAYMENT) { internalTransferExchangeWeiToPayment( transferWeiFromExchangeToPaymentVoteData.reverse, transferWeiFromExchangeToPaymentVoteData.amount ); } if(voteType == VoteType.START_PAYMENT) { internalStartPayment( startPaymentVoteData.weiToShare, startPaymentVoteData.date ); } voteType = VoteType.NONE; internalResetVotingData(); } if(votesTotalNo.mul(10).div(3) > 5) { voteType = VoteType.NONE; internalResetVotingData(); } d.voteYes = voteYes; d.lastVoteId = voteId; } function voteCancelCurrent() external onlyAdmin { require(voteType != VoteType.NONE); VoteData storage d = balances[msg.sender].vote; if(d.lastVoteId <= voteId || !d.voteCancel) { d.voteCancel = true; d.lastVoteId = voteId; voteCancel++; } uint votesCalc = voteCancel.mul(10); // 3 admins votesCalc = votesCalc.div(3); // 5 / 10 means something is voted out if(votesCalc > 5) { voteType = VoteType.NONE; internalResetVotingData(); } } function addEthForSell() external payable onlyAdmin { require(msg.value > 0); weiFromExchange = weiFromExchange.add(msg.value); } function addEthForPayment() external payable { weiForPayment = weiForPayment.add(msg.value); } function buyEPU() public payable { // how many units has client bought uint amount = msg.value.div(weiBuyPrice); uint b = balances[buyBalanceAdmin].balance; // can't buy more than main account balance if(amount >= b) { amount = b; } // the needed price for bought units uint price = amount.mul(weiBuyPrice); weiFromExchange = weiFromExchange.add(price); if(amount > 0) { buySum.price = buySum.price.add(price); buySum.amount = buySum.amount.add(amount); internalAllowTransfer(msg.sender, amount); // send units to client internalTransfer(buyBalanceAdmin, msg.sender, amount); // emit event emit UnitsBuy(msg.sender, amount); //buyBalanceAdmin.transfer(price); } // if client sent more than needed if(msg.value > price) { // send him the rest back msg.sender.transfer(msg.value.sub(price)); } } function sellEPU(uint amount) external payable returns(uint revenue) { require(amount > 0); uint fixedAmount = amount; BalanceData storage b = balances[msg.sender]; uint balance = b.balance; uint max = balance < unitsToSell ? balance : unitsToSell; if(fixedAmount > max) { fixedAmount = max; } uint price = fixedAmount.mul(weiSellPrice); require(price > 0 && price <= weiFromExchange); sellSum.price = sellSum.price.add(price); sellSum.amount = sellSum.amount.add(amount); internalTransfer(msg.sender, sellBalanceAdmin, fixedAmount); weiFromExchange = weiFromExchange.sub(price); emit UnitsSell(msg.sender, fixedAmount); msg.sender.transfer(price); return price; } function checkPayment() external { internalCheckPayment(msg.sender); } function checkPaymentFor( address person ) external { internalCheckPayment(person); } function accountData() external view returns ( uint unitsBalance, uint payableUnits, uint totalWeiToReceive, uint weiBuyPriceForUnit, uint buyUnitsLeft, uint weiSellPriceForUnit, uint sellUnitsLeft ) { BalanceData storage b = balances[msg.sender]; unitsBalance = b.balance; if(b.balancePaymentSeries < paymentSeries) { payableUnits = unitsBalance; for(uint i = 0; i <= paymentSortId; i++) { totalWeiToReceive = totalWeiToReceive.add(getPaymentWeiPerUnit(i).mul(payableUnits)); } } else { (totalWeiToReceive, payableUnits) = getAddressWeiFromPayments(b); } weiBuyPriceForUnit = weiBuyPrice; buyUnitsLeft = balances[buyBalanceAdmin].balance; weiSellPriceForUnit = weiSellPrice; sellUnitsLeft = unitsToSell; } function getBuyUnitsInformations() external view returns( uint weiBuyPriceForUnit, uint unitsLeft ) { weiBuyPriceForUnit = weiBuyPrice; unitsLeft = balances[buyBalanceAdmin].balance; } function getSellUnitsInformations() external view returns( uint weiSellPriceForUnit, uint unitsLeft ) { weiSellPriceForUnit = weiSellPrice; unitsLeft = unitsToSell; } function checkVotingForAllowTransfer() external view onlyAdmin returns( address allowTo, uint amount, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.ALLOW_TRANSFER); return ( allowTransferVoteData.addressTo, allowTransferVoteData.amount, votesTotalYes, votesTotalNo, voteType == VoteType.ALLOW_TRANSFER ); } function checkVotingForChangeAdminAddress() external view onlyAdmin returns( uint adminId, address newAdminAddress, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.CHANGE_ADMIN_WALLET); return ( changeAdminAddressVoteData.index, changeAdminAddressVoteData.adminAddress, votesTotalYes, votesTotalNo, voteType == VoteType.CHANGE_ADMIN_WALLET ); } function checkVotingForChangeBuySellLimits() external view onlyAdmin returns( uint buyPriceMin, uint buyPriceMax, uint sellPriceMin, uint sellPriceMax, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.CHANGE_BUY_SELL_LIMITS); return ( changeBuySellLimitsVoteData.buyPriceMin, changeBuySellLimitsVoteData.buyPriceMax, changeBuySellLimitsVoteData.sellPriceMin, changeBuySellLimitsVoteData.sellPriceMax, votesTotalYes, votesTotalNo, voteType == VoteType.CHANGE_BUY_SELL_LIMITS ); } function checkVotingForChangeBuySellPrice() external view onlyAdmin returns( uint buyPrice, uint buyAddUnits, uint sellPrice, uint sellAddUnits, bool ignoreSecurityLimits, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.CHANGE_BUY_SELL_PRICE); return ( changeBuySellPriceVoteData.buyPrice, changeBuySellPriceVoteData.buyAddUnits, changeBuySellPriceVoteData.sellPrice, changeBuySellPriceVoteData.sellAddUnits, changeBuySellPriceVoteData.ignoreSecurityLimits, votesTotalYes, votesTotalNo, voteType == VoteType.CHANGE_BUY_SELL_PRICE ); } function checkVotingForSendWeiFromExchange() external view onlyAdmin returns( address addressTo, uint weiAmount, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.SEND_WEI_FROM_EXCHANGE); return ( sendWeiFromExchangeVoteData.addressTo, sendWeiFromExchangeVoteData.amount, votesTotalYes, votesTotalNo, voteType == VoteType.SEND_WEI_FROM_EXCHANGE ); } function checkVotingForSendWeiFromPayment() external view onlyAdmin returns( address addressTo, uint weiAmount, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.SEND_WEI_FROM_PAYMENT); return ( sendWeiFromPaymentVoteData.addressTo, sendWeiFromPaymentVoteData.amount, votesTotalYes, votesTotalNo, voteType == VoteType.SEND_WEI_FROM_PAYMENT ); } function checkVotingForTransferWeiFromExchangeToPayment() external view onlyAdmin returns ( bool reverse, uint amount, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.TRANSFER_EXCHANGE_WEI_TO_PAYMENT); return ( transferWeiFromExchangeToPaymentVoteData.reverse, transferWeiFromExchangeToPaymentVoteData.amount, votesTotalYes, votesTotalNo, voteType == VoteType.TRANSFER_EXCHANGE_WEI_TO_PAYMENT ); } function checkVotingForStartPayment() external view onlyAdmin returns( uint weiToShare, uint date, uint votesYes, uint votesNo, bool stillActive ) { require(voteType == VoteType.START_PAYMENT); return ( startPaymentVoteData.weiToShare, startPaymentVoteData.date, votesTotalYes, votesTotalNo, voteType == VoteType.START_PAYMENT ); } function totalSupply() public constant returns (uint) { return maxUnits - balances[mainBalanceAdmin].balance; } // important to display balance in the wallet. function balanceOf(address unitOwner) public constant returns (uint balance) { balance = balances[unitOwner].balance; } function transferFrom( address from, address to, uint units ) public returns (bool success) { BalanceData storage b = balances[from]; uint a = b.allowed[msg.sender]; a = a.sub(units); b.allowed[msg.sender] = a; success = internalTransfer(from, to, units); } function approve( address spender, uint units ) public returns (bool success) { balances[msg.sender].allowed[spender] = units; emit Approval(msg.sender, spender, units); success = true; } function allowance( address unitOwner, address spender ) public constant returns (uint remaining) { remaining = balances[unitOwner].allowed[spender]; } function transfer( address to, uint value ) public returns (bool success) { return internalTransfer(msg.sender, to, value); } function getMaskForPaymentBytes() private pure returns(bytes32) { return bytes32(uint(2**32 - 1)); } function getPaymentBytesIndexSize(uint index) private pure returns (uint) { return 32 * index; } function getPaymentWeiPerUnit(uint index) private view returns(uint weiPerUnit) { bytes32 mask = getMaskForPaymentBytes(); uint offsetIndex = getPaymentBytesIndexSize(index); mask = shiftLeft(mask, offsetIndex); bytes32 before = paymentHistory & mask; weiPerUnit = uint(shiftRight(before, offsetIndex)).mul(1000000000000); } //bytes32 private dataBytes; function getMask() private pure returns (bytes32) { return bytes32(uint(2**32 - 1)); } function getBitIndex(uint index) private pure returns (uint) { return 32 * index; } function shiftLeft (bytes32 a, uint n) private pure returns (bytes32) { uint shifted = uint(a) * 2 ** uint(n); return bytes32(shifted); } function shiftRight (bytes32 a, uint n) private pure returns (bytes32) { uint shifted = uint(a) / 2 ** uint(n); return bytes32(shifted); } function internalStartVoting() private onlyAdmin { internalResetVotingData(); voteId = voteId.add(1); } function internalResetVotingData() private onlyAdmin { votesTotalYes = 0; votesTotalNo = 0; voteCancel = 0; } function internalAllowTransfer( address from, uint amount ) private { BalanceData storage b = balances[from]; b.transferAllowed = b.transferAllowed.add(amount); } function internalChangeAdminWallet( uint index, address addr ) private onlyAdmin { // adding 'else' for each index costs more gas if(index == 0) { internalTransferAccount(mainBalanceAdmin, addr); mainBalanceAdmin = addr; } if(index == 1) { internalTransferAccount(buyBalanceAdmin, addr); buyBalanceAdmin = addr; } if(index == 2) { internalTransferAccount(sellBalanceAdmin, addr); sellBalanceAdmin = addr; } } function internalAddBuyUnits( uint price, uint addUnits, bool ignoreLimits ) private onlyAdmin { if(price > 0) { weiBuyPrice = price; if(!ignoreLimits && securityWeiBuyPriceFrom > 0 && weiBuyPrice < securityWeiBuyPriceFrom) { weiBuyPrice = securityWeiBuyPriceFrom; } if(!ignoreLimits && securityWeiBuyPriceTo > 0 && weiBuyPrice > securityWeiBuyPriceTo) { weiBuyPrice = securityWeiBuyPriceTo; } } if(addUnits > 0) { uint b = balances[mainBalanceAdmin].balance; if(addUnits > b) { addUnits = b; } internalAllowTransfer(buyBalanceAdmin, addUnits); internalTransfer(mainBalanceAdmin, buyBalanceAdmin, addUnits); } emit OnExchangeBuyUpdate(weiBuyPrice, balances[buyBalanceAdmin].balance); } function internalAddSellUnits( uint price, uint addUnits, bool ignoreLimits ) private onlyAdmin { if(price > 0) { weiSellPrice = price; if(!ignoreLimits) { if(securityWeiSellPriceFrom > 0 && weiSellPrice < securityWeiSellPriceFrom) { weiSellPrice = securityWeiSellPriceFrom; } if(securityWeiSellPriceTo > 0 && weiSellPrice > securityWeiSellPriceTo) { weiSellPrice = securityWeiSellPriceTo; } } } if(addUnits > 0) { unitsToSell = unitsToSell.add(addUnits); //uint requireWei = unitsToSell * weiSellPrice; uint maxUnitsAccountCanBuy = sellBalanceAdmin.balance.div(weiSellPrice); if(unitsToSell > maxUnitsAccountCanBuy) { unitsToSell = maxUnitsAccountCanBuy; } //internalTransfer(mainBalanceAdmin, sellBalanceAdmin, unitsToSell); //balances[mainBalanceAdmin] = balances[mainBalanceAdmin].sub(unitsToSell); } emit OnExchangeSellUpdate(weiSellPrice, unitsToSell); } function internalChangeBuySellLimits( uint buyPriceMin, uint buyPriceMax, uint sellPriceMin, uint sellPriceMax ) private onlyAdmin { if(buyPriceMin > 0) { securityWeiBuyPriceFrom = buyPriceMin; } if(buyPriceMax > 0) { securityWeiBuyPriceTo = buyPriceMax; } if(sellPriceMin > 0) { securityWeiSellPriceFrom = sellPriceMin; } if(sellPriceMax > 0) { securityWeiSellPriceTo = sellPriceMax; } } function internalChangeBuySellPrice( uint buyPrice, uint buyAddUnits, uint sellPrice, uint sellAddUnits, bool ignoreSecurityLimits ) private onlyAdmin { internalAddBuyUnits(buyPrice, buyAddUnits, ignoreSecurityLimits); internalAddSellUnits(sellPrice, sellAddUnits, ignoreSecurityLimits); } // Executed when there is too much wei on the exchange function internalSendWeiFromExchange( address addressTo, uint amount ) private onlyAdmin { internalRemoveWeiFromExchange(amount); addressTo.transfer(amount); } function internalTransferExchangeWeiToPayment(bool reverse, uint amount) private onlyAdmin { if(reverse) { weiFromExchange = weiFromExchange.add(amount); weiForPayment = weiForPayment.sub(amount); } else { internalRemoveWeiFromExchange(amount); weiForPayment = weiForPayment.add(amount); } } function internalRemoveWeiFromExchange(uint amount) private onlyAdmin { weiFromExchange = weiFromExchange.sub(amount); uint units = weiFromExchange.div(weiSellPrice); if(units < unitsToSell) { unitsToSell = units; } } function internalSendWeiFromPayment( address addressTo, uint amount ) private onlyAdmin { weiForPayment = weiForPayment.sub(amount); addressTo.transfer(amount); } function getAmountOfUnitsOnPaymentId( BalanceData storage b, uint index ) private view returns(uint) { bytes32 mask = getMask(); uint offsetIndex = getBitIndex(index); mask = shiftLeft(mask, offsetIndex); bytes32 before = b.paymentBalances & mask; before = shiftRight(before, offsetIndex); uint r = uint(before); // special case of error if(r > amountOfUnitsOutsideAdminWallet) { return 0; } return r; } function setAmountOfUnitsOnPaymentId( BalanceData storage b, uint index, uint value ) private { bytes32 mask = getMask(); uint offsetIndex = getBitIndex(index); mask = shiftLeft(mask, offsetIndex); b.paymentBalances = (b.paymentBalances ^ mask) & b.paymentBalances; bytes32 field = bytes32(value); field = shiftLeft(field, offsetIndex); b.paymentBalances = b.paymentBalances | field; } function internalTransferAccount( address addrA, address addrB ) private onlyAdmin { if(addrA != 0x0 && addrB != 0x0) { BalanceData storage from = balances[addrA]; BalanceData storage to = balances[addrB]; if(from.balancePaymentSeries < paymentSeries) { from.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(from, 0, from.balance); from.balancePaymentSeries = paymentSeries; } if(to.balancePaymentSeries < paymentSeries) { to.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(to, 0, to.balance); to.balancePaymentSeries = paymentSeries; } uint nextPaymentFirstUnits = getAmountOfUnitsOnPaymentId(from, 0); setAmountOfUnitsOnPaymentId(from, 0, 0); setAmountOfUnitsOnPaymentId(to, 1, nextPaymentFirstUnits); for(uint i = 0; i <= 5; i++) { uint existingUnits = getAmountOfUnitsOnPaymentId(from, i); existingUnits = existingUnits.add(getAmountOfUnitsOnPaymentId(to, i)); setAmountOfUnitsOnPaymentId(from, i, 0); setAmountOfUnitsOnPaymentId(to, i, existingUnits); } to.balance = to.balance.add(from.balance); from.balance = 0; } } // metamask error with start payment? Ensure if it's not dividing by 0! function internalStartPayment(uint weiTotal, uint date) private onlyAdmin { require(weiTotal >= amountOfUnitsOutsideAdminWallet); paymentNumber = paymentNumber.add(1); paymentSortId = paymentNumber % 6; if(paymentSortId == 0) { paymentHistory = bytes32(0); paymentSeries = paymentSeries.add(1); uint weiLeft = totalAmountOfWeiOnPaymentsPerSeries.sub(totalAmountOfWeiPaidToUsersPerSeries); if(weiLeft > 0) { weiForPayment = weiForPayment.add(weiLeft); } totalAmountOfWeiPaidToUsersPerSeries = 0; totalAmountOfWeiOnPaymentsPerSeries = 0; } buySum.price = 0; buySum.amount = 0; sellSum.price = 0; sellSum.amount = 0; bytes32 mask = getMaskForPaymentBytes(); uint offsetIndex = getPaymentBytesIndexSize(paymentSortId); mask = shiftLeft(mask, offsetIndex); paymentHistory = (paymentHistory ^ mask) & paymentHistory; // amount of microether (1 / 1 000 000 eth) per unit bytes32 field = bytes32((weiTotal.div(1000000000000)).div(amountOfUnitsOutsideAdminWallet)); field = shiftLeft(field, offsetIndex); paymentHistory = paymentHistory | field; weiForPayment = weiForPayment.sub(weiTotal); totalAmountOfWeiOnPaymentsPerSeries = totalAmountOfWeiOnPaymentsPerSeries.add(weiTotal); internalCheckPayment(buyBalanceAdmin); internalCheckPayment(sellBalanceAdmin); lastPaymentDate = date; emit NewPayment(paymentNumber, weiTotal, amountOfUnitsOutsideAdminWallet, lastPaymentDate); } function internalCheckPayment(address person) private { require(person != mainBalanceAdmin); BalanceData storage b = balances[person]; if(b.balancePaymentSeries < paymentSeries) { b.balancePaymentSeries = paymentSeries; b.paymentBalances = bytes32(b.balance); } (uint weiToSendSum, uint unitsReceived) = getAddressWeiFromPayments(b); b.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(b, paymentSortId.add(1), b.balance); if(weiToSendSum > 0) { totalAmountOfWeiPaidToUsers = totalAmountOfWeiPaidToUsers.add(weiToSendSum); totalAmountOfWeiPaidToUsersPerSeries = totalAmountOfWeiPaidToUsersPerSeries.add(weiToSendSum); emit PaymentReceived(person, paymentNumber, weiToSendSum, unitsReceived); person.transfer(weiToSendSum); } } function getAddressWeiFromPayments(BalanceData storage b) private view returns(uint weiSum, uint unitsSum) { for(uint i = 0; i <= paymentSortId; i++) { unitsSum = unitsSum.add(getAmountOfUnitsOnPaymentId(b, i)); weiSum = weiSum.add(getPaymentWeiPerUnit(i).mul(unitsSum)); } } function proceedTransferFromMainAdmin(BalanceData storage bT, uint value) private { if(bT.balancePaymentSeries < paymentSeries) { bT.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(bT, 0, bT.balance); bT.balancePaymentSeries = paymentSeries; } amountOfUnitsOutsideAdminWallet = amountOfUnitsOutsideAdminWallet.add(value); uint fixedNewPayment = paymentNumber.add(1); uint curr = getAmountOfUnitsOnPaymentId(bT, fixedNewPayment).add(value); setAmountOfUnitsOnPaymentId(bT, fixedNewPayment, curr); } function proceedTransferToMainAdmin(BalanceData storage bF, uint value) private { amountOfUnitsOutsideAdminWallet = amountOfUnitsOutsideAdminWallet.sub(value); if(bF.balancePaymentSeries < paymentSeries) { bF.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(bF, 0, bF.balance); bF.balancePaymentSeries = paymentSeries; } uint maxVal = paymentSortId.add(1); for(uint i = 0; i <= maxVal; i++) { uint v = getAmountOfUnitsOnPaymentId(bF, i); if(v >= value) { setAmountOfUnitsOnPaymentId(bF, i, v.sub(value)); break; } value = value.sub(v); setAmountOfUnitsOnPaymentId(bF, i, 0); } } function proceedTransferFromUserToUser(BalanceData storage bF, BalanceData storage bT, uint value) private { if(bF.balancePaymentSeries < paymentSeries) { bF.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(bF, 0, bF.balance); bF.balancePaymentSeries = paymentSeries; } if(bT.balancePaymentSeries < paymentSeries) { bT.paymentBalances = bytes32(0); setAmountOfUnitsOnPaymentId(bT, 0, bT.balance); bT.balancePaymentSeries = paymentSeries; } uint maxVal = paymentSortId.add(1); for(uint i = 0; i <= maxVal; i++) { uint fromAmount = getAmountOfUnitsOnPaymentId(bF, i); uint toAmount = getAmountOfUnitsOnPaymentId(bT, i); if(fromAmount >= value) { setAmountOfUnitsOnPaymentId(bT, i, toAmount.add(value)); setAmountOfUnitsOnPaymentId(bF, i, fromAmount.sub(value)); break; } value = value.sub(fromAmount); setAmountOfUnitsOnPaymentId(bT, i, toAmount.add(fromAmount)); setAmountOfUnitsOnPaymentId(bF, i, 0); } } function internalTransfer( address from, address to, uint value ) private returns (bool success) { BalanceData storage bF = balances[from]; BalanceData storage bT = balances[to]; if(to == 0x0 || bF.balance < value) { return false; } bool fromMainAdmin = from == mainBalanceAdmin; bool fromAdminToNonAdmin = isAdmin(from) && !isAdmin(to); if(fromMainAdmin || fromAdminToNonAdmin) { assert(bT.transferAllowed > 0); if(value > bT.transferAllowed) { value = bT.transferAllowed; } bT.transferAllowed = bT.transferAllowed.sub(value); } if(to == sellBalanceAdmin) { require(unitsToSell > 0); if(value > unitsToSell) { value = unitsToSell; } unitsToSell = unitsToSell.sub(value); } if(fromMainAdmin) { proceedTransferFromMainAdmin(bT, value); emit OnEmitNewUnitsFromMainWallet(value, amountOfUnitsOutsideAdminWallet); } else if(to == mainBalanceAdmin) { proceedTransferToMainAdmin(bF, value); emit OnAddNewUnitsToMainWallet(value, amountOfUnitsOutsideAdminWallet); } else { proceedTransferFromUserToUser(bF, bT, value); } bF.balance = bF.balance.sub(value); bT.balance = bT.balance.add(value); emit Transfer(from, to, value); return true; } function isAdmin(address person) private view returns(bool) { return (person == mainBalanceAdmin || person == buyBalanceAdmin || person == sellBalanceAdmin); } }
adding 'else' for each index costs more gas
function internalChangeAdminWallet( uint index, address addr ) private onlyAdmin { if(index == 0) { internalTransferAccount(mainBalanceAdmin, addr); mainBalanceAdmin = addr; } if(index == 1) { internalTransferAccount(buyBalanceAdmin, addr); buyBalanceAdmin = addr; } if(index == 2) { internalTransferAccount(sellBalanceAdmin, addr); sellBalanceAdmin = addr; } }
12,717,099
./partial_match/3/0x02D2FDCA7d73adbF48e9D581622075B4531BA68f/sources/FIRE.sol
Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; }
5,206,786
/** * @title Membership * @notice This contract stores basic modifiers which control the membership * @dev The contract consists of the functionality of crowdsale-like token generation and basic functions of user management. */ pragma solidity ^0.4.21; import "./Accessible.sol"; import "./ProposalInterface.sol"; //@TODO To introduce the feature of DAOToken later. This feature and the feature of reputation, along with the rewarding system can be introduced later. // import "./DAOToken.sol"; //@TODO The SafeMath contract is used for calculating membership contribution. import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol"; //@TODO Other wallet or addresses to be imported in the contract... contract Membership is Accessible, Ownable { using SafeMath for uint256; // using SafeERC20 for DAOToken; ProposalInterface proposalGate; // DAOToken public nativeToken; address public treasuryAdr; address public gaManagerAdr; uint256 public headcount = 1; uint256 private lastNoDelegateTime = 0; uint256 public constant personalContribution = 10000 wei; // The contribution (in wei) that each person needs to pay mapping(address=>uint256) internal memberContribution; // This is sepecially used when a minimum contribution is needed but not restrict to this value. mapping(address=>uint256) internal voteWeight; mapping(address=>address) internal firstWhiteLister; /** *@param concernedWhitelister The account of the whitelister. *@param removedOrAdded If a whitelister is newly added, true; If removed, false */ event ChangeInWhitelister(address indexed concernedWhitelister, bool removedOrAdded); event ChangeInMembershipStatus(address indexed accountAddress, uint currentStatus); event ChangeInDelegate(address indexed concernedDelegate, bool removedOrAdded); modifier treasuryOnly { require(msg.sender == treasuryAdr); _; } /** *@title The constructor of the contract *@notice By default, the contract deployer is the delegate (holds the admin right, at the very first beginning) *@dev Whitelisters need to be provided upon construction. *@param _nativeToken the voting token used in the DAAS. However, at the current stage, no token is needed. * Token can then be introduced later when a staking mechanism is introduced. *@param _whitelisterOne the account address of the first whitelister *@param _whitelisterTwo the account address of the second whitelister */ constructor (address _delegate, address _whitelisterOne, address _whitelisterTwo) public { delegate = _delegate; // nativeToken = _nativeToken; //@TODO linked the token. mint token and later transfer the ownership of the token to this contact address. whitelisterList[0] = _whitelisterOne; whitelisterList[1] = _whitelisterTwo; // whitelisterList.push(_whitelisterOne); // whitelisterList.push(_whitelisterTwo); membershipList[_delegate] = membershipStatus.isMember; // By default, the delegate is also a member. emit ChangeInDelegate(delegate, true); emit ChangeInWhitelister(_whitelisterOne, true); emit ChangeInWhitelister(_whitelisterTwo, true); emit ChangeInMembershipStatus(delegate, uint(membershipStatus.isMember)); } // new function for update proposals function updateProposalContractAddress(address _newProposal) public onlyOwner { require(_newProposal != 0x0); proposalGate = ProposalInterface(_newProposal); } function updateTreasuryAddress(address _newTreasury) public onlyOwner { require(_newTreasury != 0x0); treasuryAdr = _newTreasury; } function updateGAContractAddress(address _newGA) public onlyOwner { require(_newGA != 0x0); gaManagerAdr = _newGA; } // // // separate the update contract function into two small ones // function updateContractAddress(address _newProposal, address _newTreasury) public onlyOwner { // require(_newProposal != 0x0 || _newTreasury != 0x0); // if (_newProposal != 0x0) { // proposalGate = ProposalInterface(_newProposal); // } // if (_newTreasury != 0x0) { // treasuryAdr = _newTreasury; // } // } /** *@title A non-member requests the membership from the DAAS. *@notice Set the status of the member into requesting if the particular account has not yet done the request. */ function requestMembership() public returns (bool) { require(membershipList[msg.sender] == membershipStatus.nonMember); membershipList[msg.sender] = membershipStatus.requesting; emit ChangeInMembershipStatus(msg.sender, uint(membershipStatus.requesting)); return true; } /** *@title Check the status of membership status: requesting or not *@dev Check whether this should be implemented as a modifier *@param _adr The address of the to-be-verified account */ function isRequestingMembership(address _adr) private view returns (bool) { if (membershipList[_adr] == membershipStatus.requesting) { return true; } else { return false; } } /** *@title Check the status of membership status: whitelisted or not *@dev Check whether this should be implemented as a modifier *@param _adr The address of the to-be-verified account */ function isWhitelisted(address _adr) private view returns (bool) { if (membershipList[_adr] == membershipStatus.whitelistedByOne || membershipList[_adr] == membershipStatus.whitelistedByTwo) { return true; } else { return false; } } /** *@notice Set up the status of the member into the desired one. *@dev Can only be called internally by other functions. *@param _adr Account address that needs to be set into another status *@param _status The corresponding membershipStatus, as per defined in the Accessible.sol */ function setMembershipStatus(address _adr, uint _status) private returns (bool) { //@TODO Need to compare the gas cost with hard-coded lines. membershipList[_adr] = membershipStatus(_status); emit ChangeInMembershipStatus(msg.sender, _status); return true; } /** *@title Add another whitelister. *@dev Only delegate has the right to add another whitelister. *@notice The new whitelister does not need to be a member of the DAAS. Theoretically, delegate can also take over the role of whitelister. *@param _adr The address of the new whitelister */ function addWhitelister(address _adr) public delegateOnly returns (bool) { require(isWhitelister(_adr) == false); whitelisterList[whitelisterListLength] = _adr; whitelisterListLength++; // whitelisterList.push(_adr); emit ChangeInWhitelister(_adr,true); return true; } /** *@title Remove whitelister *@notice This action can only be called by delegate. Firstly, check the length of the whitelister's list. */ function removeWhitelister(address _adr) public delegateOnly returns (bool) { require(isWhitelister(_adr) == true); require(whitelisterListLength > MINIMUM_WHITELISTER); for (uint i = 0; i < whitelisterListLength-1; i++) { if (whitelisterList[i] == _adr) { break; } } if (i != whitelisterListLength-1) { whitelisterList[i] = whitelisterList[whitelisterListLength-1]; } whitelisterListLength--; emit ChangeInWhitelister(_adr,false); return true; } /** *@notice Whitelisters can give their approvals regarding the application of new members *@dev Check whether add a modifier, if isRequesting is implemented as modifier */ function whitelistMember(address _adr) public whitelisterOnly returns (bool) { require(membershipList[_adr] == membershipStatus.requesting || (membershipList[_adr] == membershipStatus.whitelistedByOne && firstWhiteLister[_adr] != msg.sender)); if (membershipList[_adr] == membershipStatus.requesting) { membershipList[_adr] = membershipStatus.whitelistedByOne; firstWhiteLister[_adr] = msg.sender; emit ChangeInMembershipStatus(_adr, uint(membershipStatus.whitelistedByOne)); } else { membershipList[_adr] = membershipStatus.whitelistedByTwo; emit ChangeInMembershipStatus(_adr, uint(membershipStatus.whitelistedByTwo)); } return true; } // /** // *@notice To pay membership if needed. If the person is not a member the transaction cannot pass through. // *@dev Evaluate how to define the membership unit price. Whether hardcoded or not / In which form: identical price for all or depending on the membershipStatus. // * Link to the fallback function. // * When the person or entity is a member or ready to be a member, it is allowed to deposit money in to the contract. Then contract transfer money to the wallet address. // */ // function payMembership() public payable returns (bool) { // require(msg.value >= personalContribution); // // call function of treasuryInterface and forward the money. // } function addNewMember(address _newMember) public returns (bool) { //treasuryOnly require(msg.sender == treasuryAdr); require(membershipList[_newMember] == membershipStatus.whitelistedByTwo); membershipList[_newMember] = membershipStatus.isMember; headcount++; } // /** // *@notice Whether need to move to the wallet contract // */ // function enablePayout() public returns (bool) { // //@TODO Should be called by proposal contract when the proposal is passed with success. // } /** *@title To remove a member from the association *@notice Can only be triggered by a valid proposal or also possible for delegate to expel a member? */ function removeMember(address _adr) public returns (bool) { require(membershipList[_adr] == membershipStatus.isMember); //@TODO require(verify msg.sender == purposal address) Also need to make sure that the purposal contract is actuallly pertinent to the removal of a member. //@TODO refund its membership contribution? membershipList[_adr] = membershipStatus.nonMember; headcount--; emit ChangeInMembershipStatus(_adr, uint(membershipStatus.nonMember)); } /** *@title Set the account address of the delegate. *@dev This can only be successfully called by the GA purposal (upon sucess of voting..) */ function setDelegate(address _adr) public returns (bool) { require(msg.sender == gaManagerAdr); //@TODO require(verify msg.sender == GA purposal address) require(membershipList[_adr] == membershipStatus.isMember); emit ChangeInDelegate(delegate, true); } /** *@notice To see the membership status of a particular address *@param _adr The address of the to-be-checked account */ function getMembershipStatus(address _adr) public view returns (uint) { return uint256(membershipList[_adr]); } function expelMember(bytes32 _proposalID) public returns (bool) { // upon proposal success require(proposalGate.getProposalFinalResult(_proposalID)); // request is dissolve require(proposalGate.checkActionIsExpel(_proposalID)); address _expelledMember; _expelledMember = proposalGate.getProposalProposedAdr(_proposalID); // Cannot expel delegate require(_expelledMember != delegate); membershipList[_expelledMember] = membershipStatus.nonMember; return true; } /** *@notice Get important information. */ function getDelegate() public view returns (address) { return delegate; } function checkIsMember(address _adr) external view returns (bool) { return (membershipList[_adr] == membershipStatus.isMember); } function checkIsDelegate(address _adr) external view returns (bool) { return (delegate == _adr); } function checkIsWhitelistedByTwo(address _adr) external view returns (bool) { return (membershipList[_adr] == membershipStatus.whitelistedByTwo); } function reachDesiredValue(uint256 _value) external view returns (bool) { if (_value < personalContribution) { return false; } else { return true; } } function hasDelegate() external view returns (bool) { return (delegate != 0x0); } function getWhitelisterNumber() public view returns (uint256) { return whitelisterListLength; } function getTotalMemberNumber() public view returns (uint256) { return headcount; } }
Add another whitelister. Only delegate has the right to add another whitelister. The new whitelister does not need to be a member of the DAAS. Theoretically, delegate can also take over the role of whitelister. _adr The address of the new whitelister/ whitelisterList.push(_adr);
function addWhitelister(address _adr) public delegateOnly returns (bool) { require(isWhitelister(_adr) == false); whitelisterList[whitelisterListLength] = _adr; whitelisterListLength++; emit ChangeInWhitelister(_adr,true); return true; }
12,611,507
pragma solidity ^0.5.0; import "./TrivialGame.sol"; import "./Safemath.sol"; /** @title Tournament */ contract Tournament { using SafeMath for uint; // // State Variables // // An array of registrants. Every registrant needs to be payable address payable[] public registrants; // Keep an array of the games to be played in the tournament TrivialGame[] public games; // Keep track of the number of players uint public numberOfPlayers; // Setting max number of players uint public maxPlayers; // We will eventually set a winner address payable public winner; // The host of the tournament address payable public host; // There is a registration fee for the tournament so we can give prize money uint public registrationFee; // Keep track of how much money has been collected uint public totalMoneyCollected; // The percent of funds that host gets uint public rakePercent; // Circuit Breaker in case of an emergency bool private emergencyStop; // // Functions // /// @notice Creates a new Tournament. This tournament is hard coded to /// play a TrivialGame. /// @dev Hard code your own configurations // - registrationFee is currently not configurable // - maxPlayers is currently not configurable // - rakePercent is currently not configurable constructor () public { host = msg.sender; // .1 Ether as a registration fee registrationFee = 100000000000000000; totalMoneyCollected = 0; rakePercent = 10; numberOfPlayers = 0; maxPlayers = 8; winner = address(0); emergencyStop = false; } /// @notice - register a player in the tournament function register() public payable notStopped notHost onlyRegisterOnce checkAmountTransferred tournamentStarted checkPlayerCap { numberOfPlayers = numberOfPlayers.add(1); registrants.push(msg.sender); totalMoneyCollected = totalMoneyCollected.add(msg.value); emit MoneyCollected(totalMoneyCollected); emit ConfirmRegistrant(msg.sender); } /// @notice - The host can begin the tournament when they like /// @dev - The tournament can only be started if there are more than one registrants function startTournament() public notStopped onlyHost moreThanOnePlayer { for (uint i = 0; i < numberOfPlayers - 1; i++) { games.push(new TrivialGame()); emit CreateGame(games[i]); } emit StartTournament(); } /// @notice - Distributes funds to the winner of the tournament and the host function distributeFunds() public payable notStopped checkLastGame { // Set the winner winner = games[numberOfPlayers - 2].winner(); // Transfer rakePercent / 100 of the contracts balance to the host to compensate for gas uint hostRake = address(this).balance.div(rakePercent); host.transfer(hostRake); // Transfer the winner the rest of the balance uint prizeMoney = address(this).balance; winner.transfer(prizeMoney); emit TournamentEnd(winner); emit PrizeMoney(prizeMoney); emit HostRake(hostRake); } /// @notice - Gives host capability to stop the tournament /// @dev - EmergencyStop trigger 'notStopped' modifier on all functions function circuitBreaker() public payable onlyHost notStopped { emergencyStop = true; for (uint i = 0; i < registrants.length; i++) { registrants[i].transfer(registrationFee); } } // // Events // event ConfirmRegistrant( address registrantAddress ); event MoneyCollected( uint value ); event TournamentEnd( address winner ); event PrizeMoney( uint prizeMoney ); event HostRake( uint hostRake ); event StartTournament(); event CreateGame( TrivialGame game ); // // Modifiers // modifier onlyHost() {require (msg.sender == host, "Only host can use this function"); _;} modifier checkAmountTransferred() {require (msg.value == registrationFee, "Insuffcient funds transferred"); _;} modifier checkPlayerCap() {require (numberOfPlayers < maxPlayers, "Max players reached"); _;} modifier checkLastGame() {require (games[numberOfPlayers - 2].winner() != address(0), "Last Game has not been played"); _;} modifier notHost() {require (msg.sender != host, "Host cannot participate in the tournament"); _;} modifier notStopped() {require(!emergencyStop, "Emergency Stop Button was Pressed"); _;} modifier tournamentStarted() {require (games.length == 0, "Tournament has already begun"); _;} modifier moreThanOnePlayer() {require (numberOfPlayers > 1, "A tournament cannot be played by one registrant"); _;} modifier onlyRegisterOnce() { for (uint i = 0; i < registrants.length; i++) { require (msg.sender != registrants[i], "Cannot register a player more than once"); } _; } }
- The host can begin the tournament when they like - The tournament can only be started if there are more than one registrants
function startTournament() public notStopped onlyHost moreThanOnePlayer { for (uint i = 0; i < numberOfPlayers - 1; i++) { games.push(new TrivialGame()); emit CreateGame(games[i]); } emit StartTournament(); }
6,392,791
./partial_match/1/0x521dd9162786CDB4DfE66E137958f194dC6770db/sources/contracts/v3/interfaces/IERC721PepeV3.sol
ERC-721 Non-Fungible Token Standard, optional enumeration extension/
interface IERC721PepeV3 is IERC721 { function setBaseURI(string memory uri) external; function setPepeMinter(address _minter) external; function setAuthorizedSigningAddress(address signer) external; function mint(address to, uint256 imageHash) external; function burn(uint256 _tokenId) external; function tokenId() external returns (uint256); }
2,602,750
pragma solidity 0.4.26; import "./ISovrynSwapNetwork.sol"; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/ISovrynSwapFormula.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/ReentrancyGuard.sol"; import "./utility/TokenHolder.sol"; import "./utility/SafeMath.sol"; import "./token/interfaces/IEtherToken.sol"; import "./token/interfaces/ISmartToken.sol"; import "./sovrynswapx/interfaces/ISovrynSwapX.sol"; // interface of older converters for backward compatibility contract ILegacyConverter { function change( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn ) public returns (uint256); } /** * @dev The SovrynSwapNetwork contract is the main entry point for SovrynSwap token conversions. * It also allows for the conversion of any token in the SovrynSwap Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the SovrynSwap Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract SovrynSwapNetwork is ISovrynSwapNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000; uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000; address private constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping(address => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( address indexed _smartToken, address indexed _fromToken, address indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new SovrynSwapNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public ContractRegistryClient(_registry) { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[]) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected target amount of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected target amount */ function rateByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = _path[i - 2]; IERC20Token anchor = _path[i - 1]; IERC20Token targetToken = _path[i]; converter = IConverter(IConverterAnchor(anchor).owner()); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (targetToken == anchor) { // buy the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.add(amount); } else if (sourceToken == anchor) { // sell the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the sovrynSwap network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(_path[0], IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == 0) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = _path[_path.length - 1]; ISovrynSwapX sovrynSwapX = ISovrynSwapX(addressOf(SOVRYNSWAP_X)); // verify that the destination token is BNT require(targetToken == addressOf(BNT_TOKEN), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, this, _affiliateAccount, _affiliateFee); // grant SovrynSwapX allowance ensureAllowance(targetToken, sovrynSwapX, amount); // transfer the resulting amount to SovrynSwapX sovrynSwapX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the SovrynSwapNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * SovrynSwapX contract directly by specifying the conversion id * * @param _path conversion path * @param _sovrynSwapX address of the SovrynSwapX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion( IERC20Token[] _path, ISovrynSwapX _sovrynSwapX, uint256 _conversionId, uint256 _minReturn, address _beneficiary ) public returns (uint256) { // verify that the source token is the SovrynSwapX token require(_path[0] == _sovrynSwapX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from SovrynSwapX contract uint256 amount = _sovrynSwapX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, stepData.converter, fromAmount); } // older converter // if the source token is the smart token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != ISmartToken(stepData.anchor)) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert.value(msg.value)( stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary ); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken( IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount ) private { IConverter firstConverter = IConverter(_anchor.owner()); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, this, _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(_sourceToken).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount); else safeTransferFrom(_sourceToken, msg.sender, this, _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion target amount * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken( ConversionStep[] _data, uint256 _amount, address _beneficiary ) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(targetToken).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData( IERC20Token[] _conversionPath, address _beneficiary, bool _affiliateFeeEnabled ) private view returns (ConversionStep[]) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; address bntToken = addressOf(BNT_TOKEN); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(anchor.owner()); IERC20Token targetToken = _conversionPath[i + 2]; // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ anchor: // set the converter anchor anchor, converter: // set the converter converter, sourceToken: // set the source/target tokens _conversionPath[i], targetToken: targetToken, beneficiary: // requires knowledge about the next step, so initialize in the next phase address(0), isV28OrHigherConverter: // set flags isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = this; // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = data[i + 1].converter; // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = this; } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = this; } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(this, _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (address) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { address reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return IERC20Token(ETH_RESERVE_ADDRESS); return IERC20Token(getConverterEtherTokenAddress(_converter)); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using assembly code since older converter versions have different return values function getReturn( address _dest, address _sourceToken, address _targetToken, uint256 _amount ) internal view returns (uint256, uint256) { uint256[2] memory ret; bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); assembly { let success := staticcall( gas, // gas remaining _dest, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 64 // output length ) if iszero(success) { revert(0, 0) } } return (ret[0], ret[1]); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using assembly code to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bool success; uint256[1] memory ret; bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); assembly { success := staticcall( 5000, // isV28OrHigher consumes 190 gas, but just for extra safety _converter, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 32 // output length ) } return success && ret[0] != 0; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } }
deprecated, backward compatibility/
function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); }
12,943,221
pragma solidity ^0.5.15; import { ModexpInverse, ModexpSqrt } from "./ModExp.sol"; /** @title Boneh–Lynn–Shacham (BLS) signature scheme on Barreto-Naehrig 254 bit curve (BN-254) @notice We use BLS signature aggregation to reduce the size of signature data to store on chain. @dev We use G1 points for signatures and messages, and G2 points for public keys */ library BLS { // Field order // prettier-ignore uint256 private constant N = 21888242871839275222246405745257275088696311157297823662689037894645226208583; // Negated genarator of G2 // prettier-ignore uint256 private constant N_G2_X1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634; // prettier-ignore uint256 private constant N_G2_X0 = 10857046999023057135944570762232829481370756359578518086990519993285655852781; // prettier-ignore uint256 private constant N_G2_Y1 = 17805874995975841540914202342111839520379459829704422454583296818431106115052; // prettier-ignore uint256 private constant N_G2_Y0 = 13392588948715843804641432497768002650278120570034223513918757245338268106653; // sqrt(-3) // prettier-ignore uint256 private constant Z0 = 0x0000000000000000b3c4d79d41a91759a9e4c7e359b6b89eaec68e62effffffd; // (sqrt(-3) - 1) / 2 // prettier-ignore uint256 private constant Z1 = 0x000000000000000059e26bcea0d48bacd4f263f1acdb5c4f5763473177fffffe; // prettier-ignore uint256 private constant T24 = 0x1000000000000000000000000000000000000000000000000; // prettier-ignore uint256 private constant MASK24 = 0xffffffffffffffffffffffffffffffffffffffffffffffff; function verifySingle( uint256[2] memory signature, uint256[4] memory pubkey, uint256[2] memory message ) internal view returns (bool, bool) { uint256[12] memory input = [ signature[0], signature[1], N_G2_X1, N_G2_X0, N_G2_Y1, N_G2_Y0, message[0], message[1], pubkey[1], pubkey[0], pubkey[3], pubkey[2] ]; uint256[1] memory out; uint256 precompileGasCost = pairingPrecompileCallGasCost(2); bool callSuccess; // solium-disable-next-line security/no-inline-assembly assembly { callSuccess := staticcall( precompileGasCost, 8, input, 384, out, 0x20 ) } if (!callSuccess) { return (false, false); } return (out[0] != 0, true); } function verifyMultiple( uint256[2] memory signature, uint256[4][] memory pubkeys, uint256[2][] memory messages ) internal view returns (bool checkResult, bool callSuccess) { uint256 size = pubkeys.length; require(size > 0, "BLS: number of public key is zero"); require( size == messages.length, "BLS: number of public keys and messages must be equal" ); uint256 inputSize = (size + 1) * 6; uint256[] memory input = new uint256[](inputSize); input[0] = signature[0]; input[1] = signature[1]; input[2] = N_G2_X1; input[3] = N_G2_X0; input[4] = N_G2_Y1; input[5] = N_G2_Y0; for (uint256 i = 0; i < size; i++) { input[i * 6 + 6] = messages[i][0]; input[i * 6 + 7] = messages[i][1]; input[i * 6 + 8] = pubkeys[i][1]; input[i * 6 + 9] = pubkeys[i][0]; input[i * 6 + 10] = pubkeys[i][3]; input[i * 6 + 11] = pubkeys[i][2]; } uint256[1] memory out; uint256 precompileGasCost = pairingPrecompileCallGasCost(size); // solium-disable-next-line security/no-inline-assembly assembly { callSuccess := staticcall( precompileGasCost, 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20 ) } if (!callSuccess) { return (false, false); } return (out[0] != 0, true); } function pairingPrecompileCallGasCost(uint256 pubkeyLen) internal pure returns (uint256) { uint256 base = 45000; uint256 pair = 34000; return base + pair * (pubkeyLen + 1); } /** @notice Fouque-Tibouchi Hash to Curve */ function hashToPoint(bytes32 domain, bytes memory message) internal view returns (uint256[2] memory) { uint256[2] memory u = hashToField(domain, message); uint256[2] memory p0 = mapToPoint(u[0]); uint256[2] memory p1 = mapToPoint(u[1]); uint256[4] memory bnAddInput; bnAddInput[0] = p0[0]; bnAddInput[1] = p0[1]; bnAddInput[2] = p1[0]; bnAddInput[3] = p1[1]; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, bnAddInput, 128, p0, 64) switch success case 0 { invalid() } } require(success, "BLS: bn add call failed"); return p0; } function mapToPoint(uint256 _x) internal pure returns (uint256[2] memory p) { require(_x < N, "mapToPointFT: invalid field element"); uint256 x = _x; (, bool decision) = sqrt(x); uint256 a0 = mulmod(x, x, N); a0 = addmod(a0, 4, N); uint256 a1 = mulmod(x, Z0, N); uint256 a2 = mulmod(a1, a0, N); a2 = inverse(a2); a1 = mulmod(a1, a1, N); a1 = mulmod(a1, a2, N); // x1 a1 = mulmod(x, a1, N); x = addmod(Z1, N - a1, N); // check curve a1 = mulmod(x, x, N); a1 = mulmod(a1, x, N); a1 = addmod(a1, 3, N); bool found; (a1, found) = sqrt(a1); if (found) { if (!decision) { a1 = N - a1; } return [x, a1]; } // x2 x = N - addmod(x, 1, N); // check curve a1 = mulmod(x, x, N); a1 = mulmod(a1, x, N); a1 = addmod(a1, 3, N); (a1, found) = sqrt(a1); if (found) { if (!decision) { a1 = N - a1; } return [x, a1]; } // x3 x = mulmod(a0, a0, N); x = mulmod(x, x, N); x = mulmod(x, a2, N); x = mulmod(x, a2, N); x = addmod(x, 1, N); // must be on curve a1 = mulmod(x, x, N); a1 = mulmod(a1, x, N); a1 = addmod(a1, 3, N); (a1, found) = sqrt(a1); require(found, "BLS: bad ft mapping implementation"); if (!decision) { a1 = N - a1; } return [x, a1]; } function isValidSignature(uint256[2] memory signature) internal pure returns (bool) { if ((signature[0] >= N) || (signature[1] >= N)) { return false; } else { return isOnCurveG1(signature); } } function isOnCurveG1(uint256[2] memory point) internal pure returns (bool _isOnCurve) { // solium-disable-next-line security/no-inline-assembly assembly { let t0 := mload(point) let t1 := mload(add(point, 32)) let t2 := mulmod(t0, t0, N) t2 := mulmod(t2, t0, N) t2 := addmod(t2, 3, N) t1 := mulmod(t1, t1, N) _isOnCurve := eq(t1, t2) } } function isOnCurveG2(uint256[4] memory point) internal pure returns (bool _isOnCurve) { // solium-disable-next-line security/no-inline-assembly assembly { // x0, x1 let t0 := mload(point) let t1 := mload(add(point, 32)) // x0 ^ 2 let t2 := mulmod(t0, t0, N) // x1 ^ 2 let t3 := mulmod(t1, t1, N) // 3 * x0 ^ 2 let t4 := add(add(t2, t2), t2) // 3 * x1 ^ 2 let t5 := addmod(add(t3, t3), t3, N) // x0 * (x0 ^ 2 - 3 * x1 ^ 2) t2 := mulmod(add(t2, sub(N, t5)), t0, N) // x1 * (3 * x0 ^ 2 - x1 ^ 2) t3 := mulmod(add(t4, sub(N, t3)), t1, N) // x ^ 3 + b t0 := addmod( t2, 0x2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5, N ) t1 := addmod( t3, 0x009713b03af0fed4cd2cafadeed8fdf4a74fa084e52d1852e4a2bd0685c315d2, N ) // y0, y1 t2 := mload(add(point, 64)) t3 := mload(add(point, 96)) // y ^ 2 t4 := mulmod(addmod(t2, t3, N), addmod(t2, sub(N, t3), N), N) t3 := mulmod(shl(1, t2), t3, N) // y ^ 2 == x ^ 3 + b _isOnCurve := and(eq(t0, t4), eq(t1, t3)) } } function sqrt(uint256 xx) internal pure returns (uint256 x, bool hasRoot) { x = ModexpSqrt.run(xx); hasRoot = mulmod(x, x, N) == xx; } function inverse(uint256 a) internal pure returns (uint256) { return ModexpInverse.run(a); } function hashToField(bytes32 domain, bytes memory messages) internal pure returns (uint256[2] memory) { bytes memory _msg = expandMsgTo96(domain, messages); uint256 u0; uint256 u1; uint256 a0; uint256 a1; // solium-disable-next-line security/no-inline-assembly assembly { let p := add(_msg, 24) u1 := and(mload(p), MASK24) p := add(_msg, 48) u0 := and(mload(p), MASK24) a0 := addmod(mulmod(u1, T24, N), u0, N) p := add(_msg, 72) u1 := and(mload(p), MASK24) p := add(_msg, 96) u0 := and(mload(p), MASK24) a1 := addmod(mulmod(u1, T24, N), u0, N) } return [a0, a1]; } function expandMsgTo96(bytes32 domain, bytes memory message) internal pure returns (bytes memory) { // zero<64>|msg<var>|lib_str<2>|I2OSP(0, 1)<1>|dst<var>|dst_len<1> uint256 t0 = message.length; bytes memory msg0 = new bytes(32 + t0 + 64 + 4); bytes memory out = new bytes(96); // b0 // solium-disable-next-line security/no-inline-assembly assembly { let p := add(msg0, 96) for { let z := 0 } lt(z, t0) { z := add(z, 32) } { mstore(add(p, z), mload(add(message, add(z, 32)))) } p := add(p, t0) mstore8(p, 0) p := add(p, 1) mstore8(p, 96) p := add(p, 1) mstore8(p, 0) p := add(p, 1) mstore(p, domain) p := add(p, 32) mstore8(p, 32) } bytes32 b0 = sha256(msg0); bytes32 bi; t0 = 32 + 34; // resize intermediate message // solium-disable-next-line security/no-inline-assembly assembly { mstore(msg0, t0) } // b1 // solium-disable-next-line security/no-inline-assembly assembly { mstore(add(msg0, 32), b0) mstore8(add(msg0, 64), 1) mstore(add(msg0, 65), domain) mstore8(add(msg0, add(32, 65)), 32) } bi = sha256(msg0); // solium-disable-next-line security/no-inline-assembly assembly { mstore(add(out, 32), bi) } // b2 // solium-disable-next-line security/no-inline-assembly assembly { let t := xor(b0, bi) mstore(add(msg0, 32), t) mstore8(add(msg0, 64), 2) mstore(add(msg0, 65), domain) mstore8(add(msg0, add(32, 65)), 32) } bi = sha256(msg0); // solium-disable-next-line security/no-inline-assembly assembly { mstore(add(out, 64), bi) } // b3 // solium-disable-next-line security/no-inline-assembly assembly { let t := xor(b0, bi) mstore(add(msg0, 32), t) mstore8(add(msg0, 64), 3) mstore(add(msg0, 65), domain) mstore8(add(msg0, add(32, 65)), 32) } bi = sha256(msg0); // solium-disable-next-line security/no-inline-assembly assembly { mstore(add(out, 96), bi) } return out; } }
/ solium-disable-next-line security/no-inline-assembly
function hashToPoint(bytes32 domain, bytes memory message) internal view returns (uint256[2] memory) { uint256[2] memory u = hashToField(domain, message); uint256[2] memory p0 = mapToPoint(u[0]); uint256[2] memory p1 = mapToPoint(u[1]); uint256[4] memory bnAddInput; bnAddInput[0] = p0[0]; bnAddInput[1] = p0[1]; bnAddInput[2] = p1[0]; bnAddInput[3] = p1[1]; bool success; assembly { success := staticcall(sub(gas(), 2000), 6, bnAddInput, 128, p0, 64) switch success case 0 { invalid() } } require(success, "BLS: bn add call failed"); return p0; }
1,769,801
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // @author: greenbunny.eth /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::c:::,...........,::::c::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::;'....,:. ,::' .::,......'::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::'...;cc:cdx;..,,;c:,,;cccccc,...,::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::,.,:'.oo,',cxocclloxocc;'',,,,:ll:..,c:::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::,.'l:,codc..::,,,,:xo'.,,;ccccccok:...';:::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::c, .llcll;'..'cdddlco:':ddc,'',..,l;.cl..;::::::::::::::::::::::::::::::::: :::::::::::::::::::::::c:,'.''. .;odlcccldxc,,:ddllc:::c;''';cdd..;c:::::::::::::::::::::::::::::::: :::::::::::::::::::::::c;..dkk; 'cc,..'',okllxkkl,''','',:ox,.cd. .;:::::::::::::::::::::::::::::::: ::::::::::::::::::::::::;..;okl,,,,. 'xOko;..,::::::::cxl.,xo;;;..,,';:::::::::::::::::::::::::::::: ::::::::::::::::::::::::;..,okOklcxxclko;. ':;;;. .::;;' ,xo;:::oOc .:::::::::::::::::::::::::::::: :::::::::::::::::::::::,. .,;,,,..lkOd;. .,;;;cxo::;;dxl::;,:lk0Od:,',:::::::::::::::::::::::::::::: :::::::::::::::::::::'.,;;;;;;. ..,,;c' ,lc,..'lkx; .;dd;;lxOl,''';:::::::::::::::::::::::::::::::: :::::::::::::::::::::;,'';::::::c;..;;'..':ll:' ,dxoccc,;lxkl;:;..,::::::::::::::::::::::::::::::::: :::::::::::::::::::::::;,...'';:ol..lc..''',;c;..',',ll';ko';ldl. .;::::::::::::::::::::::::::::::: ::::::::::::::::::::::::;..l:..,cc'':ll,.......;;;;:c;,cdOc ;doc'...',,,;::::::::::::::::::::::::::: :::::::::::::::::::::::c;..c:'.',;c;.'oc...........;oc,.'l; ,o:;oxxxxc'''',::::::::::::::::::::::::: ::::::::::::::::::::::::::'.,xl''',,..;ldl;. .... .;;,,,,,'';okxxxdccc:;..;c::::::::::::::::::::::: ::::::::::::::::::::::::::;.':dx, .','.';;;;;;;;;;;;:dkkOkkxxxl::::' ..,;,,:c::::::::::::::::::::::: ::::::::::::::::::::::::::::;.,;:,. ...';okOkkOkkkkOkkdc;;;;;;;;;;;,.,cdd;..,::::::::::::::::::::::: ::::::::::::::::::::::::::;'..,cxkl:;;:;,;;,;;,,,,;;;;;;::;;;:oxkkxxoxkkd;..,::::::::::::::::::::::: ::::::::::::::::::::::::;.'lc,,;lkkxxo;;::::::::::::::cdxxxxxxxxxxxxxKXd;,,:c::::::::::::::::::::::: :::::::::::::::::::::::'..;ooc;,'''.',cox:'''''''''..''......'...'...',',;:::::::::::::::::::::::::: :::::::::::::::::::::::;'.,dO0xoddolcccdOdcccccclcc'.,;. 'c..;, .,c::::::::::::::::::::::::: :::::::::::::::::::::::::;,,lOxloxxdlllodoldxxxxxxxxo:'.....:xdl;....;l. ,:::::::::::::::::::::::::: :::::::::::::::::::::::::::;,'..,codoxOKXOdxxxxkOOOOOxdxxdddddkOxxxo:ox:.';:::;,;::::::::::::::::::: ::::::::::::::::::::::::::::::::. ,::cdOKkdxkxkO00000000000Ol;d0000o,lO0d..;::;,:::::::::::::::::::: ::::::::::::::::::::::::::::::;'. .. .,cdddxkxkO0000OdlllllldkkkkOkkkO0K0lcdoc:::::::::::::::::::::: ::::::::::::::::::::::::::::;'. .''''. .;cdxxxk00000Ol;;;;;;okkkkkkkkO0K0OOOdccc:::::::::::::::::::: ::::::::::::::::::::::::::;'. .''',,'''. .;lxxkkOOO00000000000000000000koc:::::::::::::::::::::::::: ::::::::::::::::::::::::;'. .''',,,,;,'''...;oxdxkkOOOOOO0OOOOOOOOOo;;;oxl:::::::::::::::::::::::::: ::::::::::::::::::::::::,. ..,,,,,,,,,,''......:xkkkkkkkkkkkkkxko;. .':lc:::::::::::::::::::::::::: :::::::::::::::::::::::.. ....',;,,;,',;'.'.. .....''''''''.... .';::::::::::::::::::::::::::: ::::::::::::::::::::::;. .......',,,,,'.. .. .,;cdxxxxxd' .,:::::::::::::::::::::::::: :::::::::::::::::::::;,. .........',,.. ..... ..'cx0KXNNNX0:.. ,c::::::::::::::::::::::::: :::::::::::::::::::;,. ............. ............'ckXNWWWWN0:..... .;::::::::::::::::::::::::: :::::::::::::::::::' . ...........................'ckXNWWWWWXc...... . .;:::::::::::::::::::::::: */ // Minting factory for TheBunnyMint contract TheBunnyMint is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl { // Keep track of the minting counters, nft types and proces using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; // this is all ERC-721, so there is a token ID // permission roles for this contract - love me some OpenZepplin 4.x bytes32 public constant TREASURER_ROLE = keccak256("TREASURER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // Setup the token URI for all nft types string private _baseTokenURI = "https://gateway.pinata.cloud/ipfs/"; // events that the contract emits event WelcomeToTheBunnyMint(uint256 id); // NFT Coonfiguration uint256 private _nftSupply = 499; // how many nfts uint256 private _forSaleSupply = 499; // how many nfts uint256 private _nftPrice = 0; // how much retail price bool private _nftAvailableForSale = false; // available for sale? // # Token Supply uint256 private _totalMintedCount = 0; uint256 private _saleMintedCount = 0; // Where the funds will go address public _mintTreasury = 0xd92599904c5A3cdD40BCf12eF8c32f7071691258; address public _donkeyDAOGuildTreasury = 0x542fAB1Ab936E5523AEfAF2026593236bB4F12FE; bool private _ticketMode = true; bytes32 private _ticketValue; // ---------------------------------------------------------------------------------------------- // Construct this... constructor() ERC721("TheBunnyMint", "TBMGEN0") { // set the permissions _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); _grantRole(TREASURER_ROLE, msg.sender); // burn ID 0 - it's not used _tokenIdCounter.increment(); // set the treasury _mintTreasury = msg.sender; _donkeyDAOGuildTreasury = msg.sender; } // ---------------------------------------------------------------------------------------------- // These are all configuration funbctions // setup nft and allow for future expansion function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyRole(MINTER_ROLE) { _baseTokenURI = baseURI; } // ---------------------------------------------------------------------------------------------- // Price management and how much supply is available, and what is contract state function getPrice() public view returns (uint256) { // return premint discount price return _nftPrice; } function getTotalSupply() public view returns (uint256) { // return premint discount price return _nftSupply; } function getAvailableSupply() public view returns (uint256) { // return premint discount price return _forSaleSupply; } // ---------------------------------------------------------------------------------------------- // Sale and Token managment function isAvailableForSale() public view returns (bool) { // make sure we are not sold out if ( isSoldOut() ) return false; else return _nftAvailableForSale; } function isSoldOut() public view returns (bool) { return ( _forSaleSupply == 0 ? true : false ); } function howManyCanMint() public view returns (uint256) { return( _nftSupply ); } // for all of you looking at the code, I totally know this shit is not secure, we should use a merkle proof // but I wanted to create a deterrent for the spammers and n00bs function setTicket(string memory _value) public onlyRole(MINTER_ROLE) { _ticketValue = keccak256(abi.encodePacked(_value)); _ticketMode = true; } function clearTicket() public onlyRole(MINTER_ROLE) { _ticketMode = false; } // ---------------------------------------------------------------------------------------------- // Mint Mangment and making sure it all works right // emergancy token URI swapping out - It's needed - sometimes your IPFS provider is down and you need to // send a hardcoded URL into mint function and then fix it later function setTokenURI( uint256 tokenId, string memory _uri ) public { if ( !hasRole(MINTER_ROLE, msg.sender ) ) { require( ownerOf(tokenId) != msg.sender, "No permission to update!" ); } _setTokenURI( tokenId, _uri ); } function _mintToken( address _to, string memory _uri) private { // let's mint the actual token - no checks required uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint( _to, tokenId ); _setTokenURI( tokenId, _uri ); _forSaleSupply = _forSaleSupply - 1; emit WelcomeToTheBunnyMint( tokenId ); } function bunnyMint( address _to, string memory _uri, string memory _ticket ) public payable { // is the nft type available for sale require( isAvailableForSale(), "Not for sale" ); // is there enough supply available require( _forSaleSupply >= 1, "Sold Out" ); if ( _ticketMode == true ) require( keccak256(abi.encodePacked(_ticket)) == _ticketValue, "Invalid mint ticket" ); // Mint it! _mintToken( _to, _uri ); } function bunnyMintReserve( address _to, uint256 quantity, string memory _uri ) public onlyRole(MINTER_ROLE) { // is there enough supply available require( _forSaleSupply >= quantity, "Sold Out" ); // Mint it! for( uint i=0; i < quantity; i++ ) _mintToken( _to, _uri ); } // you must be the admin or the owner of the NFT to burn it function burnNFT(uint256 _tokenId) public { if ( !hasRole(DEFAULT_ADMIN_ROLE, msg.sender ) ) { require( ownerOf(_tokenId) != msg.sender, "No permision to burn!" ); } _burn( _tokenId ); } // ---------------------------------------------------------------------------------------------- // allow switching of treasury and withdrawall of funds function setTreasury( address _newMintTreasury, address _newDonkeyDAOGuildTreasury ) public onlyRole(TREASURER_ROLE) { _mintTreasury = _newMintTreasury; _donkeyDAOGuildTreasury = _newDonkeyDAOGuildTreasury; } function withdrawAll() public onlyRole(TREASURER_ROLE) { uint256 balance = address(this).balance; require(balance > 0, "Empty balance"); _widthdraw( _mintTreasury, balance.mul(50).div(100) ); _widthdraw( _donkeyDAOGuildTreasury, balance.mul(50).div(100) ); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } // ---------------------------------------------------------------------------------------------- // Managment functions provided by OpenZepplin that were not touched function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function totalToken() public view returns (uint256) { return _tokenIdCounter.current()-1; } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) onlyRole(DEFAULT_ADMIN_ROLE) { super._burn(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/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 (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/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/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 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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; }
return premint discount price
function getPrice() public view returns (uint256) { return _nftPrice; }
12,073,028
pragma solidity ^0.8.0; // Copyright 2020 Keyko GmbH. // This product includes software developed at BigchainDB GmbH and Ocean Protocol // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './AgreementStoreLibrary.sol'; import '../conditions/ConditionStoreManager.sol'; import '../conditions/LockPaymentCondition.sol'; import '../registry/DIDRegistry.sol'; import '../templates/TemplateStoreManager.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; /** * @title Agreement Store Manager * @author Keyko & Ocean Protocol * * @dev Implementation of the Agreement Store. * * The agreement store generates conditions for an agreement template. * Agreement templates must to be approved in the Template Store * Each agreement is linked to the DID of an asset. */ contract AgreementStoreManager is OwnableUpgradeable, AccessControlUpgradeable { bytes32 private constant PROXY_ROLE = keccak256('PROXY_ROLE'); function grantProxyRole(address _address) public onlyOwner { grantRole(PROXY_ROLE, _address); } function revokeProxyRole(address _address) public onlyOwner { revokeRole(PROXY_ROLE, _address); } /** * @dev The Agreement Store Library takes care of the basic storage functions */ using AgreementStoreLibrary for AgreementStoreLibrary.AgreementList; /** * @dev state storage for the agreements */ AgreementStoreLibrary.AgreementList internal agreementList; ConditionStoreManager internal conditionStoreManager; TemplateStoreManager internal templateStoreManager; DIDRegistry internal didRegistry; /** * @dev initialize AgreementStoreManager Initializer * Initializes Ownable. Only on contract creation. * @param _owner refers to the owner of the contract * @param _conditionStoreManagerAddress is the address of the connected condition store * @param _templateStoreManagerAddress is the address of the connected template store * @param _didRegistryAddress is the address of the connected DID Registry */ function initialize( address _owner, address _conditionStoreManagerAddress, address _templateStoreManagerAddress, address _didRegistryAddress ) public initializer { require( _owner != address(0) && _conditionStoreManagerAddress != address(0) && _templateStoreManagerAddress != address(0) && _didRegistryAddress != address(0), 'Invalid address' ); OwnableUpgradeable.__Ownable_init(); transferOwnership(_owner); conditionStoreManager = ConditionStoreManager( _conditionStoreManagerAddress ); templateStoreManager = TemplateStoreManager( _templateStoreManagerAddress ); didRegistry = DIDRegistry( _didRegistryAddress ); _setupRole(DEFAULT_ADMIN_ROLE, _owner); } /** * @dev Create a new agreement and associate the agreement created to the address originating the transaction. * The agreement will create conditions of conditionType with conditionId. * Only "approved" templates can access this function. * @param _id is the ID of the new agreement. Must be unique. * @param _did is the bytes32 DID of the asset. The DID must be registered beforehand. * @param _conditionTypes is a list of addresses that point to Condition contracts. * @param _conditionIds is a list of bytes32 content-addressed Condition IDs * @param _timeLocks is a list of uint time lock values associated to each Condition * @param _timeOuts is a list of uint time out values associated to each Condition * @return size the size of the agreement list after the create action. */ function createAgreement( bytes32 _id, bytes32 _did, address[] memory _conditionTypes, bytes32[] memory _conditionIds, uint[] memory _timeLocks, uint[] memory _timeOuts ) public returns (uint size) { return createAgreement( _id, _did, _conditionTypes, _conditionIds, _timeLocks, _timeOuts, tx.origin // solhint-disable avoid-tx-origin ); } /** * @dev Create a new agreement. * The agreement will create conditions of conditionType with conditionId. * Only "approved" templates can access this function. * @param _id is the ID of the new agreement. Must be unique. * @param _did is the bytes32 DID of the asset. The DID must be registered beforehand. * @param _conditionTypes is a list of addresses that point to Condition contracts. * @param _conditionIds is a list of bytes32 content-addressed Condition IDs * @param _timeLocks is a list of uint time lock values associated to each Condition * @param _timeOuts is a list of uint time out values associated to each Condition * @param _creator address of the account associated as agreement and conditions creator * @return size the size of the agreement list after the create action. */ function createAgreement( bytes32 _id, bytes32 _did, address[] memory _conditionTypes, bytes32[] memory _conditionIds, uint[] memory _timeLocks, uint[] memory _timeOuts, address _creator ) public returns (uint size) { require( templateStoreManager.isTemplateApproved(msg.sender) == true, 'Template not Approved' ); require( didRegistry.getBlockNumberUpdated(_did) > 0, 'DID not registered' ); require( _conditionIds.length == _conditionTypes.length && _timeLocks.length == _conditionTypes.length && _timeOuts.length == _conditionTypes.length, 'Arguments have wrong length' ); // create the conditions in condition store. Fail if conditionId already exists. for (uint256 i = 0; i < _conditionTypes.length; i++) { conditionStoreManager.createCondition( _conditionIds[i], _conditionTypes[i], _timeLocks[i], _timeOuts[i], _creator ); } agreementList.create( _id, _did, msg.sender, _conditionIds ); // same as above return getAgreementListSize(); } function createAgreementAndPay( bytes32 _id, bytes32 _did, address[] memory _conditionTypes, bytes32[] memory _conditionIds, uint[] memory _timeLocks, uint[] memory _timeOuts, address _creator, uint _idx, address payable _rewardAddress, address _tokenAddress, uint256[] memory _amounts, address[] memory _receivers ) public payable { require(hasRole(PROXY_ROLE, msg.sender), 'Invalid access role'); createAgreement(_id, _did, _conditionTypes, _conditionIds, _timeLocks, _timeOuts, _creator); LockPaymentCondition(_conditionTypes[_idx]).fulfillProxy(_creator, _id, _did, _rewardAddress, _tokenAddress, _amounts, _receivers); } /** * @dev Get agreement with _id. * The agreement will create conditions of conditionType with conditionId. * Only "approved" templates can access this function. * @param _id is the ID of the agreement. * @return did * @return didOwner * @return templateId * @return conditionIds * @return lastUpdatedBy * @return blockNumberUpdated */ function getAgreement(bytes32 _id) external view returns ( bytes32 did, address didOwner, address templateId, bytes32[] memory conditionIds, address lastUpdatedBy, uint256 blockNumberUpdated ) { did = agreementList.agreements[_id].did; didOwner = didRegistry.getDIDOwner(did); templateId = agreementList.agreements[_id].templateId; conditionIds = agreementList.agreements[_id].conditionIds; lastUpdatedBy = agreementList.agreements[_id].lastUpdatedBy; blockNumberUpdated = agreementList.agreements[_id].blockNumberUpdated; } /** * @dev get the DID owner for this agreement with _id. * @param _id is the ID of the agreement. * @return didOwner the DID owner associated with agreement.did from the DID registry. */ function getAgreementDIDOwner(bytes32 _id) external view returns (address didOwner) { bytes32 did = agreementList.agreements[_id].did; return didRegistry.getDIDOwner(did); } /** * @dev check the DID owner for this agreement with _id. * @param _id is the ID of the agreement. * @param _owner is the DID owner * @return the DID owner associated with agreement.did from the DID registry. */ function isAgreementDIDOwner(bytes32 _id, address _owner) external view returns (bool) { bytes32 did = agreementList.agreements[_id].did; return (_owner == didRegistry.getDIDOwner(did)); } /** * @dev isAgreementDIDProvider for a given agreement Id * and address check whether a DID provider is associated with this agreement * @param _id is the ID of the agreement * @param _provider is the DID provider * @return true if a DID provider is associated with the agreement ID */ function isAgreementDIDProvider(bytes32 _id, address _provider) external view returns(bool) { bytes32 did = agreementList.agreements[_id].did; return didRegistry.isDIDProvider(did, _provider); } /** * @return size the length of the agreement list. */ function getAgreementListSize() public view virtual returns (uint size) { return agreementList.agreementIds.length; } /** * @param _did is the bytes32 DID of the asset. * @return the agreement IDs for a given DID */ function getAgreementIdsForDID(bytes32 _did) public view returns (bytes32[] memory) { return agreementList.didToAgreementIds[_did]; } /** * @param _templateId is the address of the agreement template. * @return the agreement IDs for a given DID */ function getAgreementIdsForTemplateId(address _templateId) public view returns (bytes32[] memory) { return agreementList.templateIdToAgreementIds[_templateId]; } /** * @dev getDIDRegistryAddress utility function * used by other contracts or any EOA. * @return the DIDRegistry address */ function getDIDRegistryAddress() public view returns(address) { return address(didRegistry); } }
getDIDRegistryAddress utility function used by other contracts or any EOA. return the DIDRegistry address/
function getDIDRegistryAddress() public view returns(address) { return address(didRegistry); }
2,473,894
./full_match/42/0xEFB3CeDbe8d6C3FE0c0772013a42eDA72B9c87c7/sources/browser/MockDai.sol
Operator mints dino cash to a recipient recipient_ The address of recipient amount_ The amount of dino cash to mint to return whether the process has been done/
function mint(address recipient_, uint256 amount_) public onlyOwner returns (bool) { uint256 balanceBefore = balanceOf(recipient_); _mint(recipient_, amount_); uint256 balanceAfter = balanceOf(recipient_); return balanceAfter > balanceBefore; }
16,205,973
pragma solidity ^0.4.24; // File: contracts\openzeppelin-solidity\contracts\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts\openzeppelin-solidity\contracts\lifecycle\Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts\openzeppelin-solidity\contracts\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } 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 _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts\openzeppelin-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) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts\openzeppelin-solidity\contracts\token\ERC20\MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts\openzeppelin-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 { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: contracts\AccountLockableToken.sol /** * @title Account Lockable Token */ contract AccountLockableToken is Ownable { mapping(address => bool) public lockStates; event LockAccount(address indexed lockAccount); event UnlockAccount(address indexed unlockAccount); /** * @dev Throws if called by locked account */ modifier whenNotLocked() { require(!lockStates[msg.sender]); _; } /** * @dev Lock target account * @param _target Target account to lock */ function lockAccount(address _target) public onlyOwner returns (bool) { require(_target != owner); require(!lockStates[_target]); lockStates[_target] = true; emit LockAccount(_target); return true; } /** * @dev Unlock target account * @param _target Target account to unlock */ function unlockAccount(address _target) public onlyOwner returns (bool) { require(_target != owner); require(lockStates[_target]); lockStates[_target] = false; emit UnlockAccount(_target); return true; } } // File: contracts\WithdrawableToken.sol /** * @title Withdrawable token * @dev Token that can be the withdrawal. */ contract WithdrawableToken is BasicToken, Ownable { using SafeMath for uint256; bool public withdrawingFinished = false; event Withdraw(address _from, address _to, uint256 _value); event WithdrawFinished(); modifier canWithdraw() { require(!withdrawingFinished); _; } modifier hasWithdrawPermission() { require(msg.sender == owner); _; } /** * @dev Withdraw the amount of tokens to onwer. * @param _from address The address which owner want to withdraw tokens form. * @param _value uint256 the amount of tokens to be transferred. */ function withdraw(address _from, uint256 _value) public hasWithdrawPermission canWithdraw returns (bool) { require(_value <= balances[_from]); balances[_from] = balances[_from].sub(_value); balances[owner] = balances[owner].add(_value); emit Transfer(_from, owner, _value); emit Withdraw(_from, owner, _value); return true; } /** * @dev Withdraw the amount of tokens to another. * @param _from address The address which owner want to withdraw tokens from. * @param _to address The address which owner want to transfer to. * @param _value uint256 the amount of tokens to be transferred. */ function withdrawFrom(address _from, address _to, uint256 _value) public hasWithdrawPermission canWithdraw returns (bool) { require(_value <= balances[_from]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); emit Withdraw(_from, _to, _value); return true; } /** * @dev Function to stop withdrawing new tokens. * @return True if the operation was successful. */ function finishingWithdrawing() public onlyOwner canWithdraw returns (bool) { withdrawingFinished = true; emit WithdrawFinished(); return true; } } // File: contracts\MilestoneLockToken.sol /** * @title Milestone Lock Token * @dev Token lock that can be the milestone policy applied. */ contract MilestoneLockToken is StandardToken, Ownable { using SafeMath for uint256; struct Policy { uint256 kickOff; uint256[] periods; uint8[] percentages; } struct MilestoneLock { uint8[] policies; uint256[] standardBalances; } uint8 constant MAX_POLICY = 100; uint256 constant MAX_PERCENTAGE = 100; mapping(uint8 => Policy) internal policies; mapping(address => MilestoneLock) internal milestoneLocks; event SetPolicyKickOff(uint8 policy, uint256 kickOff); event PolicyAdded(uint8 policy); event PolicyRemoved(uint8 policy); event PolicyAttributeAdded(uint8 policy, uint256 period, uint8 percentage); event PolicyAttributeRemoved(uint8 policy, uint256 period); event PolicyAttributeModified(uint8 policy, uint256 period, uint8 percentage); /** * @dev Transfer token for a specified address when enough available unlock balance. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(getAvailableBalance(msg.sender) >= _value); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another when enough available unlock balance. * @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(getAvailableBalance(_from) >= _value); return super.transferFrom(_from, _to, _value); } /** * @dev Distribute the amounts of tokens to from owner&#39;s balance with the milestone policy to a policy-free user. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _policy index of milestone policy to apply. */ function distributeWithPolicy(address _to, uint256 _value, uint8 _policy) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[owner]); require(_policy < MAX_POLICY); require(policies[_policy].periods.length > 0); balances[owner] = balances[owner].sub(_value); balances[_to] = balances[_to].add(_value); uint8 policyIndex = _getAppliedPolicyIndex(_to, _policy); if (policyIndex < MAX_POLICY) { milestoneLocks[_to].standardBalances[policyIndex] = milestoneLocks[_to].standardBalances[policyIndex].add(_value); } else { milestoneLocks[_to].policies.push(_policy); milestoneLocks[_to].standardBalances.push(_value); } emit Transfer(owner, _to, _value); return true; } /** * @dev add milestone policy. * @param _policy index of the milestone policy you want to add. * @param _periods periods of the milestone you want to add. * @param _percentages unlock percentages of the milestone you want to add. */ function addPolicy(uint8 _policy, uint256[] _periods, uint8[] _percentages) public onlyOwner returns (bool) { require(_policy < MAX_POLICY); require(_periods.length > 0); require(_percentages.length > 0); require(_periods.length == _percentages.length); require(policies[_policy].periods.length == 0); policies[_policy].periods = _periods; policies[_policy].percentages = _percentages; emit PolicyAdded(_policy); return true; } /** * @dev remove milestone policy. * @param _policy index of the milestone policy you want to remove. */ function removePolicy(uint8 _policy) public onlyOwner returns (bool) { require(_policy < MAX_POLICY); delete policies[_policy]; emit PolicyRemoved(_policy); return true; } /** * @dev get milestone policy information. * @param _policy index of milestone policy. */ function getPolicy(uint8 _policy) public view returns (uint256 kickOff, uint256[] periods, uint8[] percentages) { require(_policy < MAX_POLICY); return ( policies[_policy].kickOff, policies[_policy].periods, policies[_policy].percentages ); } /** * @dev set milestone policy&#39;s kickoff time. * @param _policy index of milestone poicy. * @param _time kickoff time of policy. */ function setKickOff(uint8 _policy, uint256 _time) public onlyOwner returns (bool) { require(_policy < MAX_POLICY); require(policies[_policy].periods.length > 0); policies[_policy].kickOff = _time; return true; } /** * @dev add attribute to milestone policy. * @param _policy index of milestone policy. * @param _period period of policy attribute. * @param _percentage percentage of unlocking when reaching policy. */ function addPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public onlyOwner returns (bool) { require(_policy < MAX_POLICY); Policy storage policy = policies[_policy]; for (uint256 i = 0; i < policy.periods.length; i++) { if (policy.periods[i] == _period) { revert(); return false; } } policy.periods.push(_period); policy.percentages.push(_percentage); emit PolicyAttributeAdded(_policy, _period, _percentage); return true; } /** * @dev remove attribute from milestone policy. * @param _policy index of milestone policy attribute. * @param _period period of target policy. */ function removePolicyAttribute(uint8 _policy, uint256 _period) public onlyOwner returns (bool) { require(_policy < MAX_POLICY); Policy storage policy = policies[_policy]; for (uint256 i = 0; i < policy.periods.length; i++) { if (policy.periods[i] == _period) { _removeElementAt256(policy.periods, i); _removeElementAt8(policy.percentages, i); emit PolicyAttributeRemoved(_policy, _period); return true; } } revert(); return false; } /** * @dev modify attribute from milestone policy. * @param _policy index of milestone policy. * @param _period period of target policy attribute. * @param _percentage percentage to modified. */ function modifyPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public onlyOwner returns (bool) { require(_policy < MAX_POLICY); Policy storage policy = policies[_policy]; for (uint256 i = 0; i < policy.periods.length; i++) { if (policy.periods[i] == _period) { policy.percentages[i] = _percentage; emit PolicyAttributeModified(_policy, _period, _percentage); return true; } } revert(); return false; } /** * @dev get policy&#39;s locked percentage of milestone policy from now. * @param _policy index of milestone policy for calculate locked percentage. */ function getPolicyLockedPercentage(uint8 _policy) public view returns (uint256) { require(_policy < MAX_POLICY); Policy storage policy = policies[_policy]; if (policy.periods.length == 0) { return 0; } if (policy.kickOff == 0 || policy.kickOff > now) { return MAX_PERCENTAGE; } uint256 unlockedPercentage = 0; for (uint256 i = 0; i < policy.periods.length; ++i) { if (policy.kickOff.add(policy.periods[i]) <= now) { unlockedPercentage = unlockedPercentage.add(policy.percentages[i]); } } if (unlockedPercentage > MAX_PERCENTAGE) { return 0; } return MAX_PERCENTAGE.sub(unlockedPercentage); } /** * @dev change account&#39;s milestone policy. * @param _to address for milestone policy applyed to. * @param _prevPolicy index of original milestone policy. * @param _newPolicy index of milestone policy to be changed. */ function modifyMilestoneTo(address _to, uint8 _prevPolicy, uint8 _newPolicy) public onlyOwner returns (bool) { require(_to != address(0)); require(_prevPolicy < MAX_POLICY); require(_newPolicy < MAX_POLICY); require(_prevPolicy != _newPolicy); require(policies[_prevPolicy].periods.length > 0); require(policies[_newPolicy].periods.length > 0); uint256 prevPolicyIndex = _getAppliedPolicyIndex(_to, _prevPolicy); require(prevPolicyIndex < MAX_POLICY); MilestoneLock storage milestoneLock = milestoneLocks[_to]; uint256 prevLockedBalance = milestoneLock.standardBalances[prevPolicyIndex]; uint256 newPolicyIndex = _getAppliedPolicyIndex(_to, _newPolicy); if (newPolicyIndex < MAX_POLICY) { milestoneLock.standardBalances[newPolicyIndex] = milestoneLock.standardBalances[newPolicyIndex].add(prevLockedBalance); _removeElementAt8(milestoneLock.policies, prevPolicyIndex); _removeElementAt256(milestoneLock.standardBalances, prevPolicyIndex); } else { milestoneLock.policies.push(_newPolicy); milestoneLock.standardBalances.push(prevLockedBalance); } return true; } /** * @dev remove milestone policy from account. * @param _from address for applied milestone policy removes from. * @param _policy index of milestone policy remove. */ function removeMilestoneFrom(address _from, uint8 _policy) public onlyOwner returns (bool) { require(_from != address(0)); require(_policy < MAX_POLICY); uint256 policyIndex = _getAppliedPolicyIndex(_from, _policy); require(policyIndex < MAX_POLICY); _removeElementAt8(milestoneLocks[_from].policies, policyIndex); _removeElementAt256(milestoneLocks[_from].standardBalances, policyIndex); return true; } /** * @dev get accounts milestone policy state information. * @param _account address for milestone policy applied. */ function getUserMilestone(address _account) public view returns (uint8[] accountPolicies, uint256[] accountStandardBalances) { return ( milestoneLocks[_account].policies, milestoneLocks[_account].standardBalances ); } /** * @dev available unlock balance. * @param _account address for available unlock balance. */ function getAvailableBalance(address _account) public view returns (uint256) { return balances[_account].sub(getTotalLockedBalance(_account)); } /** * @dev calcuate locked balance of milestone policy from now. * @param _account address for lock balance. * @param _policy index of applied milestone policy. */ function getLockedBalance(address _account, uint8 _policy) public view returns (uint256) { require(_policy < MAX_POLICY); uint256 policyIndex = _getAppliedPolicyIndex(_account, _policy); if (policyIndex >= MAX_POLICY) { return 0; } MilestoneLock storage milestoneLock = milestoneLocks[_account]; uint256 lockedPercentage = getPolicyLockedPercentage(milestoneLock.policies[policyIndex]); return milestoneLock.standardBalances[policyIndex].div(MAX_PERCENTAGE).mul(lockedPercentage); } /** * @dev calcuate locked balance of milestone policy from now. * @param _account address for lock balance. */ function getTotalLockedBalance(address _account) public view returns (uint256) { MilestoneLock storage milestoneLock = milestoneLocks[_account]; uint256 totalLockedBalance = 0; for (uint256 i = 0; i < milestoneLock.policies.length; i++) { totalLockedBalance = totalLockedBalance.add( getLockedBalance(_account, milestoneLock.policies[i]) ); } return totalLockedBalance; } /** * @dev get milestone policy index applied to user. * @param _to address The address which you want get to. * @param _policy index of meilstone policy applied. */ function _getAppliedPolicyIndex(address _to, uint8 _policy) internal view returns (uint8) { require(_policy < MAX_POLICY); MilestoneLock storage milestoneLock = milestoneLocks[_to]; for (uint8 i = 0; i < milestoneLock.policies.length; i++) { if (milestoneLock.policies[i] == _policy) { return i; } } return MAX_POLICY; } /** * @dev utility for uint256 array * @param _array target array * @param _index array index to remove */ function _removeElementAt256(uint256[] storage _array, uint256 _index) internal returns (bool) { if (_array.length <= _index) { return false; } for (uint256 i = _index; i < _array.length - 1; i++) { _array[i] = _array[i + 1]; } delete _array[_array.length - 1]; _array.length--; return true; } /** * @dev utility for uint8 array * @param _array target array * @param _index array index to remove */ function _removeElementAt8(uint8[] storage _array, uint256 _index) internal returns (bool) { if (_array.length <= _index) { return false; } for (uint256 i = _index; i < _array.length - 1; i++) { _array[i] = _array[i + 1]; } delete _array[_array.length - 1]; _array.length--; return true; } } // File: contracts\tHena.sol /** * @title Hena token */ contract tHena is Pausable, MintableToken, BurnableToken, AccountLockableToken, WithdrawableToken, MilestoneLockToken { uint256 constant MAX_SUFFLY = 1000000000; string public name; string public symbol; uint8 public decimals; constructor() public { name = "tHena"; symbol = "THENA"; decimals = 18; totalSupply_ = MAX_SUFFLY * 10 ** uint(decimals); balances[owner] = totalSupply_; emit Transfer(address(0), owner, totalSupply_); } function() public { revert(); } /** * @dev Transfer token for a specified address when if not paused and not locked account * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused whenNotLocked returns (bool) { return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to anther when if not paused and not locked account * @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 whenNotLocked returns (bool) { require(!lockStates[_from]); return super.transferFrom(_from, _to, _value); } /** * @dev Increase the amount of tokens that an owner allowed to a spender when if not paused and not locked account * @param _spender address which will spend the funds. * @param _addedValue amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public whenNotPaused whenNotLocked returns (bool) { return super.increaseApproval(_spender, _addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * @param _spender address which will spend the funds. * @param _subtractedValue amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused whenNotLocked returns (bool) { return super.decreaseApproval(_spender, _subtractedValue); } /** * @dev Distribute the amount of tokens to owner&#39;s balance. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function distribute(address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[owner]); balances[owner] = balances[owner].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(owner, _to, _value); return true; } /** * @dev Burns a specific amount of tokens by owner. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner { super.burn(_value); } }
Lock target account _target Target account to lock/
function lockAccount(address _target) public onlyOwner returns (bool) { require(_target != owner); require(!lockStates[_target]); lockStates[_target] = true; emit LockAccount(_target); return true; }
10,658,650
// SPDX-License-Identifier: MIT pragma solidity ^0.7.5; import "../libraries/SafeMath.sol"; import "../libraries/Address.sol"; import "../interfaces/IsFLOOR.sol"; import "../interfaces/IgFLOOR.sol"; import "../types/ERC20.sol"; contract gFLOOR is IgFLOOR, ERC20 { /* ========== DEPENDENCIES ========== */ using Address for address; using SafeMath for uint256; /* ========== MODIFIERS ========== */ modifier onlyApproved() { require(msg.sender == approved, "Only approved"); _; } /* ========== EVENTS ========== */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ========== DATA STRUCTURES ========== */ /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 fromBlock; uint256 votes; } /* ========== STATE VARIABLES ========== */ IsFLOOR public sFLOOR; address public approved; // minter bool public initialized; mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; mapping(address => uint256) public numCheckpoints; mapping(address => address) public delegates; /* ========== CONSTRUCTOR ========== */ constructor(address _sFLOOR) ERC20("Governance FLOOR", "gFLOOR", 18) { approved = msg.sender; require(_sFLOOR != address(0), "Zero address: sFLOOR"); sFLOOR = IsFLOOR(_sFLOOR); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice transfer mint rights from deployer to staking * @notice can only be done once, at the time of contract deployment * @param _staking address */ function initialize(address _staking) external onlyApproved { require(!initialized, "already initialized"); initialized = true; require(_staking != approved, "Invalid argument"); require(_staking != address(0), "Zero address found"); approved = _staking; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** @notice mint gFLOOR @param _to address @param _amount uint */ function mint(address _to, uint256 _amount) external override onlyApproved { _mint(_to, _amount); } /** @notice burn gFLOOR @param _from address @param _amount uint */ function burn(address _from, uint256 _amount) external override onlyApproved { _burn(_from, _amount); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice pull index from sFLOOR token */ function index() public view override returns (uint256) { return sFLOOR.index(); } /** @notice converts gFLOOR amount to FLOOR @param _amount uint @return uint */ function balanceFrom(uint256 _amount) public view override returns (uint256) { return _amount.mul(index()).div(10**decimals()); } /** @notice converts FLOOR amount to gFLOOR @param _amount uint @return uint */ function balanceTo(uint256 _amount) public view override returns (uint256) { return _amount.mul(10**decimals()).div(index()); } /** * @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) external view returns (uint256) { require(blockNumber < block.number, "gFLOOR::getPriorVotes: 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; } /* ========== INTERNAL FUNCTIONS ========== */ 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 _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 Ensure delegation moves when token is transferred. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { _moveDelegates(delegates[from], delegates[to], amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; // TODO(zx): Replace all instances of SafeMath with OZ implementation library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: 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, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // Only used in the BondingCalculator.sol function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; // TODO(zx): replace with OZ implementation. 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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ // function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { // require(address(this).balance >= value, "Address: insufficient balance for call"); // return _functionCallWithValue(target, data, value, errorMessage); // } function functionCallWithValue(address target, bytes memory data, uint256 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); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } /** * @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.3._ */ 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.3._ */ 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); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; import "./IERC20.sol"; interface IsFLOOR is IERC20 { function rebase( uint256 floorProfit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); function toG(uint amount) external view returns (uint); function fromG(uint amount) external view returns (uint); function changeDebt( uint256 amount, address debtor, bool add ) external; function debtBalances(address _address) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; import "./IERC20.sol"; interface IgFLOOR is IERC20 { function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; function index() external view returns (uint256); function balanceFrom(uint256 _amount) external view returns (uint256); function balanceTo(uint256 _amount) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; import "../libraries/SafeMath.sol"; import "../interfaces/IERC20.sol"; abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal immutable _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; 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); }
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require(blockNumber < block.number, "gFLOOR::getPriorVotes: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
327,387
pragma solidity ^0.4.26; /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a && c >= b); return c; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract PIG is SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; mapping(address => uint256) public freezeOf; mapping(address => mapping(address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function PIG( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply, _value); // Updates totalSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) returns (bool success) { if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) { if (msg.sender != owner) throw; owner.transfer(amount); } // can accept ether function() payable { } }
Check if the sender has enough Subtract from the sender Updates totalSupply
function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); totalSupply = SafeMath.safeSub(totalSupply, _value); Burn(msg.sender, _value); return true; }
13,537,236
./partial_match/1/0xf9539C6e9Cdd31D2c5eF02052dA2DdF9C1bee757/sources/src/core/vaults/mixins/options/BaseOptionsVault.sol
Settles the existing option(s)/
function _beforeCloseRound() internal virtual override { VaultState memory vState = vaultState; if (vState.round == 1) return; uint256 currentExpiry = roundExpiry[vState.round]; if (currentExpiry <= PLACEHOLDER_UINT) revert OV_RoundClosed(); if (currentExpiry > block.timestamp) { if (vState.totalPending == 0) revert OV_NoCollateralPending(); (Position[] memory shorts, Position[] memory longs,) = _getMarginAccount(); if (shorts.length == 0 && longs.length == 0) revert OV_RoundClosed(); _settleOptions(); } }
15,544,415
./full_match/80001/0x911122c6760Aa4843382cB3d7E3a073F56459256/sources/LP/CKCoinPair.sol
scope for _token{0,1}, avoids stack too deep errors scope for reserve{0,1} Adjusted, avoids stack too deep errors
function swap( uint256 amountCkOut, uint256 amountUsdcOut, address to ) external nonReentrant onlyCKRouter { require(amountCkOut > 0 || amountUsdcOut > 0, "Insufficient output amount"); require(amountCkOut < reserveCk && amountUsdcOut < reserveUsdc, "Insufficient liquidity"); uint256 balanceCk; uint256 balanceUsdc; { require(to != address(ck), "Cannot send to CK"); if (amountCkOut > 0) { } if (amountUsdcOut > 0) { } balanceCk = ck.balanceOf(address(this)); balanceUsdc = usdCoin.balanceOf(address(this)); } uint256 amountCkIn = balanceCk > reserveCk - amountCkOut ? balanceCk - (reserveCk - amountCkOut) : 0; uint256 amountUsdcIn = balanceUsdc > reserveUsdc - amountUsdcOut ? balanceUsdc - (reserveUsdc - amountUsdcOut) : 0; require(amountCkIn > 0 || amountUsdcIn > 0, "Insufficient input amount"); { uint256 balanceCkAdjusted = balanceCk * 100 - (amountCkIn * 1); uint256 balanceUsdcAdjusted = balanceUsdc * 100 - (amountUsdcIn * 1); require( balanceCkAdjusted * balanceUsdcAdjusted >= reserveCk * reserveUsdc * 100**2, "K slippage" ); } _reserveCk = balanceCk; _reserveUsdc = balanceUsdc; emit Swap(msg.sender, amountCkIn, amountUsdcIn, amountCkOut, amountUsdcOut, to); }
5,590,624
./full_match/4/0x5BDBa4CBF4a1fFDFe88097F48F896A64251e1abB/sources/contracts/AlejandraCollection.sol
retrieve all funds recieved from minting
function withdraw() public onlyOwner { uint256 balance = accountBalance(); require(balance > 0, 'No Funds to withdraw, Balance is 0'); _withdraw(payable(owner()), balance); }
12,480,936
pragma solidity ^0.5.0; contract ResumeCheck { struct resume { // Initialize arrays for resume data address owner; uint date; } address public creator; uint public ResumeNo; mapping(bytes32 => resume) public resumeHashMap; // Set mapping constructor() public { creator = msg.sender; ResumeNo = 0; } function NewResume(bytes32 hash) public returns (bool success) { if (ResumeExist(hash)) { // Check resume existance first success = false; // If resume already exist no resume will be added to the HashMap }else { resume storage d = resumeHashMap[hash]; // If resume does not exist, start resume addition process d.owner = msg.sender; d.date = now; ResumeNo++; // Counter for amount of resume added to the HashMap success = true; } return success; } function ResumeExist(bytes32 hash) public view returns (bool exists) { if (resumeHashMap[hash].date > 0) { // Check if resume hash exsist in the HashMap (date as the condition) exists = true; } else { exists = false; } return exists; } function CapResume(bytes32 hash) public view returns (uint date, address owner) { // Get resume hash and assign date and owner to it date = resumeHashMap[hash].date; owner = resumeHashMap[hash].owner; } function CapTotalResume() public view returns (uint resumeNo) { //Call Amount of resume from NewResume function return ResumeNo; } }
Get resume hash and assign date and owner to it
function CapResume(bytes32 hash) public view returns (uint date, address owner) {
938,490
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; pragma experimental ABIEncoderV2; import "./ethregistrar/BaseRegistrarImplementation.sol"; import "./resolvers/Resolver.sol"; import "./root/Controllable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract AMAENSClient is Controllable { string constant public TWITTER_KEY = "com.twitter"; string constant public IS_TWITTER_VERIFIED_STRING = "isTwitterverified"; string constant public NAME_STRING = "name"; string constant public AVATAR_STRING = "avatar"; string constant public TWITTERID_STRING = "twitterID"; string constant public BOOL_FALSE_STRING = "False"; string constant public BOOL_TRUE_STRING = "True"; address private baseAddr; address private resolver; uint private duration; event NameRegistered(string name, bytes32 indexed label, address indexed owner, uint expires); event NameRenewed(string name, bytes32 indexed label, uint expires); constructor(address _baseRegistrarImplementation, address _resolver, uint _duration){ baseAddr = _baseRegistrarImplementation; resolver = _resolver; duration = _duration; } /** * @dev Create a nodehash from the label with the help of the Namehash of the root domain. * @param _label The _label for the domain like test.amafans, test is the label. */ function getNodeHash(string memory _label) external view returns (bytes32,bytes32,uint256){ bytes32 label = keccak256(bytes(_label)); uint256 tokenId = uint256(label); return (label, keccak256(abi.encodePacked(BaseRegistrarImplementation(baseAddr).baseNode(), label)), tokenId); } /** * @dev Create a nodehash from the label with the help of the Namehash of the root domain. * @param _nodehash Nomehash of the full domain like Namehash(test.amafans). * @param isTwitterVerified if the user has blue tick on the twitter profile or not. * @param nameOnTwitter Name of the person as he puts it on the twitter profile. * @param twitterUsername The twitter username of the person present on the twitter profile * @param profileImage The url of the profileImage on the twitter account, this will be empty string if none is available * @param twitterID this is the only thing unique, unchanged for a twitter account since it is internal to twitter */ function _setKeyPairs(bytes32 _nodehash, bool isTwitterVerified, string memory nameOnTwitter, string memory twitterUsername, string memory profileImage, string memory twitterID ) private { bytes[] memory multiCallData = _setTextMulticall(_nodehash, isTwitterVerified, nameOnTwitter, twitterUsername, profileImage, twitterID); Resolver(resolver).multicall(multiCallData); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param tokenId The node to transfer ownership of. * @param owner The address of the new owner. */ function _transferOwnership(uint256 tokenId, address owner) private { BaseRegistrarImplementation(baseAddr).reclaim(tokenId, owner); BaseRegistrarImplementation(baseAddr).transferFrom(address(this), owner, tokenId); } function _setResolverValues(bytes32 nodehash, address _owner) private { Resolver(resolver).setAddr(nodehash, _owner); } function registerNode(address _owner, bytes memory _bytes, string memory twitterUsername) external onlyController returns (bytes32, string memory){ (string memory subdomain, string memory nameOnTwitter, string memory profileImage, uint256 twitterID, bool isTwitterVerified) = _decodeData(_bytes); // bytes32 label = keccak256(bytes(_label)); // uint256 tokenId = uint256(label); // The nodehash of this label (bytes32 label, bytes32 nodehash, uint256 tokenId) = this.getNodeHash(subdomain); //check if the tokenId is available or nor if (!BaseRegistrarImplementation(baseAddr).available(tokenId)){ revert("This domain is not available"); } uint256 expires = _register(nodehash, tokenId); // Configure the resolver _setResolverValues(nodehash, _owner); _setKeyPairs(nodehash, isTwitterVerified, nameOnTwitter, twitterUsername, profileImage, Strings.toString(twitterID)); // // Now transfer full ownership to the expeceted owner _transferOwnership(tokenId, _owner); emit NameRegistered(subdomain, label, _owner, expires); return (nodehash, subdomain); } function _register(bytes32 nodehash, uint256 tokenId) private returns(uint256){ uint256 expires =BaseRegistrarImplementation(baseAddr).register(tokenId, address(this), duration); //set key value pairs here // Set the resolver BaseRegistrarImplementation(baseAddr).ens().setResolver(nodehash, resolver); BaseRegistrarImplementation(baseAddr).ens().setTTL(nodehash, uint64(expires)); return expires; } function renew(string calldata name, uint _duration) external onlyController { bytes32 label = keccak256(bytes(name)); uint expires = BaseRegistrarImplementation(baseAddr).renew(uint256(label), _duration); emit NameRenewed(name, label, expires); } function _decodeData(bytes memory _bytes) public pure returns (string memory, string memory, string memory, uint256, bool) { (string memory username, string memory name, string memory profileImage, uint256 id, bool twitterVerified) = abi.decode(_bytes, (string,string,string,uint256,bool)); return (username, name, profileImage, id, twitterVerified); } //https://github.com/ensdomains/ens-contracts/blob/master/contracts/root/Root.sol function _setTextMulticall(bytes32 nameHash, bool isTwitterVerified, string memory nameOnTwitter, string memory twitterUsername, string memory profileImage, string memory twitterID) private pure returns(bytes[] memory){ bytes[] memory _data = new bytes[](5); if (isTwitterVerified){ _data[2] = abi.encodeWithSignature("setText(bytes32,string,string)",nameHash,IS_TWITTER_VERIFIED_STRING,BOOL_TRUE_STRING); }else{ _data[2] = abi.encodeWithSignature("setText(bytes32,string,string)",nameHash,IS_TWITTER_VERIFIED_STRING,BOOL_FALSE_STRING); } // abi.encodeWithSignature("add(uint256,uint256)", a, b) _data[0] = abi.encodeWithSignature("setText(bytes32,string,string)", nameHash, NAME_STRING, nameOnTwitter); _data[1] = abi.encodeWithSignature("setText(bytes32,string,string)",nameHash,TWITTER_KEY,twitterUsername); _data[3] = abi.encodeWithSignature("setText(bytes32,string,string)",nameHash,AVATAR_STRING,profileImage); _data[4] = abi.encodeWithSignature("setText(bytes32,string,string)",nameHash,TWITTERID_STRING,twitterID); return _data; } }
Create a nodehash from the label with the help of the Namehash of the root domain. _label The _label for the domain like test.amafans, test is the label./
function getNodeHash(string memory _label) external view returns (bytes32,bytes32,uint256){ bytes32 label = keccak256(bytes(_label)); uint256 tokenId = uint256(label); return (label, keccak256(abi.encodePacked(BaseRegistrarImplementation(baseAddr).baseNode(), label)), tokenId); }
12,912,368
//Address: 0x51ee363006b42962004fbf98b181e0b9621bf360 //Contract name: Protocol108v2 //Balance: 0 Ether //Verification Date: 2/27/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity 0.4.18; // D.H.A.R.M.A. Initiative Swan Protocol // The protocol must be executed at least once every 108 minutes // Failure to do so releases the reward to the last executor contract Protocol108 { // smart contract version uint public version = 1; // countdown timer reset value uint length = 6480; // last time protocol was executed uint offset; // last executor of the protocol address public executor; // number of times protocol was executed // zero value means protocol is in initialization state uint public cycle; // total value volume passed through uint public volume; // creates the protocol function Protocol108() public { } // initializes the protocol function initialize() public payable { // validate protocol state assert(cycle == 0); // update the protocol update(); } // executes the protocol function execute() public payable { // validate protocol state assert(cycle > 0); assert(offset + length > now); // update the protocol update(); } // withdraws the reward to the last executor function withdraw() public { // validate protocol state assert(cycle > 0); assert(offset + length <= now); // validate input(s) require(msg.sender == executor); // reset cycle count cycle = 0; // transfer the reward executor.transfer(this.balance); } // updates the protocol state by // updating offset, last executor and cycle count function update() private { // validate input(s) validate(msg.value); // update offset (last execution time) offset = now; // update last executor executor = msg.sender; // update cycle cycle++; // update total volume volume += msg.value; } // validates the input sequence of numbers // simplest impl (current): positive value // proper impl (consideration for future versions): 00..0481516234200..0-like values // where any number of leading/trailing zeroes allowed // calling this function as part of transaction returns true or throws an exception // calling this function as constant returns true or false function validate(uint sequence) public constant returns (bool) { // validate the sequence require(sequence > 0); // we won't get here if validation fails return true; } // number of seconds left until protocol terminates function countdown() public constant returns (uint) { // check if protocol is initialized if(cycle == 0) { // for uninitialized protocol its equal to length return length; } // for active/terminated protocol calculate the value uint n = now; // check for negative overflow if(offset + length > n) { // positive countdown return offset + length - n; } // zero or negative countdown return 0; } // the default payable function, performs one of // initialize(), execute() or withdraw() depending on protocol state function() public payable { if(cycle == 0) { // protocol not yet initialized, try to initialize initialize(); } else if(offset + length > now) { // protocol is eligible for execution, execute execute(); } else if(this.balance > 0) { // protocol has terminated, withdraw the reward withdraw(); } else { // invalid protocol state revert(); } } } // D.H.A.R.M.A. Initiative Swan Protocol version 2 // makes use of the sequence, 4 8 15 16 23 42 contract Protocol108v2 is Protocol108 { // smart contract version uint public version = 2; // creates the protocol, nothing to improve here function Protocol108v2() Protocol108() public { } // validates the input sequence of numbers // improvement over version 1 protocol, makes use of the sequence function validate(uint sequence) public constant returns (bool) { // save the countdown value for reuse inside the function uint c = countdown(); // validate the sequence: // require ~0.0048 ETH to initialize the protocol, // or to execute it if countdown is four minutes or more // require ~4.8 szabo to execute the protocol if // countdown is one minute or more // require ~4.8 Gwei to execute the protocol if // countdown is less then one minute require( c < 60 && ( // ~4.8+ Shannon sequence == 4815162342 || sequence == 48151623420 || sequence == 481516234200 ) || // c < 240 && ( // ~4.8 Szabo sequence == 4815162342000 || sequence == 48151623420000 || sequence == 481516234200000 ) || ( sequence == 4815162342000000 // ~0.0048 ETH || sequence == 48151623420000000 // ~0.048 ETH || sequence == 481516234200000000 // ~0.48 ETH || sequence == 4815162342000000000 // ~4.8 ETH || sequence == 48151623420000000000 // ~48 ETH || sequence == 481516234200000000000 // ~0.48 Einstein // to reduce gas costs we use seqSearch only for big numbers || seqSearch(sequence, 12, 56) != -1 // ~4.8 Einstein - ~4.8*10^55 Einstein ) ); // we won't get here if validation fails return true; } // checks if sequence can be represented in form of // 48151623420..00 where number of trailing zeroes // is between offset and offset + length; // returns number of trailing zeroes or -1 // if the sequence cannot be represented in this form function seqSearch(uint sequence, uint offset, uint length) private constant returns (int) { for(uint i = offset; i < offset + length; i++) { if(sequence == 4815162342 * 10 ** i) { // found at index i return int(i); } } // not found return -1; } }
checks if sequence can be represented in form of 48151623420..00 where number of trailing zeroes is between offset and offset + length; returns number of trailing zeroes or -1 if the sequence cannot be represented in this form found at index i
function seqSearch(uint sequence, uint offset, uint length) private constant returns (int) { for(uint i = offset; i < offset + length; i++) { if(sequence == 4815162342 * 10 ** i) { return int(i); } } }
15,805,744
pragma solidity ^0.4.24; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name = "EtherStone"; string public symbol = "ETHS"; uint256 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply = 100*1000*1000*10**decimals; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function giveBlockReward() { balanceOf[block.coinbase] += 1; } bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balanceOf[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( ) public { balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract AirdropCentral { using SafeMath for uint256; // The owner / admin of the Airdrop Central // In charge of accepting airdrop submissions address public owner; // How many tokens the owner keeps of each airdrop as transaction fee uint public ownersCut = 2; // 2% commision in tokens // Id of each airdrop (token address + id #) struct TokenAirdropID { address tokenAddress; uint airdropAddressID; // The id of the airdrop within a token address } struct TokenAirdrop { address tokenAddress; uint airdropAddressID; // The id of the airdrop within a token address address tokenOwner; uint airdropDate; // The airdrop creation date uint airdropExpirationDate; // When airdrop expires uint tokenBalance; // Current balance uint totalDropped; // Total to distribute uint usersAtDate; // How many users were signed at airdrop date } struct User { address userAddress; uint signupDate; // Determines which airdrops the user has access to // User -> Airdrop id# -> balance mapping (address => mapping (uint => uint)) withdrawnBalances; } // Maps the tokens available to airdrop central contract. Keyed by token address mapping (address => TokenAirdrop[]) public airdroppedTokens; TokenAirdropID[] public airdrops; // List of users that signed up mapping (address => User) public signups; uint public userSignupCount = 0; // Admins with permission to accept submissions mapping (address => bool) admins; // Whether or not the contract is paused (in case of a problem is detected) bool public paused = false; // List of approved/rejected token/sender addresses mapping (address => bool) public tokenWhitelist; mapping (address => bool) public tokenBlacklist; mapping (address => bool) public airdropperBlacklist; // // Modifiers // modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyAdmin { require(msg.sender == owner || admins[msg.sender]); _; } modifier ifNotPaused { require(!paused); _; } // // Events // event E_AirdropSubmitted(address _tokenAddress, address _airdropper,uint _totalTokensToDistribute,uint creationDate, uint _expirationDate); event E_Signup(address _userAddress,uint _signupDate); event E_TokensWithdrawn(address _tokenAddress,address _userAddress, uint _tokensWithdrawn, uint _withdrawalDate); function AirdropCentral() public { owner = msg.sender; } ///////////////////// // Owner / Admin functions ///////////////////// /** * @dev pause or unpause the contract in case a problem is detected */ function setPaused(bool _isPaused) public onlyOwner{ paused = _isPaused; } /** * @dev allows owner to grant/revoke admin privileges to other accounts * @param _admin is the account to be granted/revoked admin privileges * @param isAdmin is whether or not to grant or revoke privileges. */ function setAdmin(address _admin, bool isAdmin) public onlyOwner{ admins[_admin] = isAdmin; } /** * @dev removes a token and/or account from the blacklist to allow * them to submit a token again. * @param _airdropper is the account to remove from blacklist * @param _tokenAddress is the token address to remove from blacklist */ function removeFromBlacklist(address _airdropper, address _tokenAddress) public onlyOwner { if(_airdropper != address(0)) airdropperBlacklist[_airdropper] = false; if(_tokenAddress != address(0)) tokenBlacklist[_tokenAddress] = false; } /** * @dev approves a given token and account address to make it available for airdrop * This is necessary to avoid malicious contracts to be added. * @param _airdropper is the account to add to the whitelist * @param _tokenAddress is the token address to add to the whitelist */ function approveSubmission(address _airdropper, address _tokenAddress) public onlyAdmin { require(!airdropperBlacklist[_airdropper]); require(!tokenBlacklist[_tokenAddress]); tokenWhitelist[_tokenAddress] = true; } /** * @dev removes token and airdropper from whitelist. * Also adds them to a blacklist to prevent further submissions of any * To be used in case of an emgency where the owner failed to detect * a problem with the address submitted. * @param _airdropper is the account to add to the blacklist and remove from whitelist * @param _tokenAddress is the token address to add to the blacklist and remove from whitelist */ function revokeSubmission(address _airdropper, address _tokenAddress) public onlyAdmin { if(_tokenAddress != address(0)){ tokenWhitelist[_tokenAddress] = false; tokenBlacklist[_tokenAddress] = true; } if(_airdropper != address(0)){ airdropperBlacklist[_airdropper] = true; } } /** * @dev allows admins to add users to the list manually * Use to add people who explicitely asked to be added... */ function signupUsersManually(address _user) public onlyAdmin { require(signups[_user].userAddress == address(0)); signups[_user] = User(_user,now); userSignupCount++; E_Signup(msg.sender,now); } ///////////////////// // Airdropper functions ///////////////////// /** * @dev Transfers tokens to contract and sets the Token Airdrop * @notice Before calling this function, you must have given the Airdrop Central * an allowance of the tokens to distribute. * Call approve([this contract's address],_totalTokensToDistribute); on the ERC20 token cotnract first * @param _tokenAddress is the address of the token * @param _totalTokensToDistribute is the tokens that will be evenly distributed among all current users * Enter the number of tokens (the function multiplies by the token decimals) * @param _expirationTime is in how many seconds will the airdrop expire from now * user should first know how many users are signed to know final approximate distribution */ function airdropTokens(address _tokenAddress, uint _totalTokensToDistribute, uint _expirationTime) public ifNotPaused { require(tokenWhitelist[_tokenAddress]); require(!airdropperBlacklist[msg.sender]); //Multiply number entered by token decimals. // Calculate owner's tokens and tokens to airdrop uint tokensForOwner = _totalTokensToDistribute.mul(ownersCut).div(100); _totalTokensToDistribute = _totalTokensToDistribute.sub(tokensForOwner); // Store the airdrop unique id in array (token address + id) TokenAirdropID memory taid = TokenAirdropID(_tokenAddress,airdroppedTokens[_tokenAddress].length); TokenAirdrop memory ta = TokenAirdrop(_tokenAddress,airdroppedTokens[_tokenAddress].length,msg.sender,now,now+_expirationTime,_totalTokensToDistribute,_totalTokensToDistribute,userSignupCount); airdroppedTokens[_tokenAddress].push(ta); airdrops.push(taid); // Transfer the tokens E_AirdropSubmitted(_tokenAddress,ta.tokenOwner,ta.totalDropped,ta.airdropDate,ta.airdropExpirationDate); } /** * @dev returns unclaimed tokens to the airdropper after the airdrop expires * @param _tokenAddress is the address of the token */ function returnTokensToAirdropper(address _tokenAddress) public ifNotPaused { require(tokenWhitelist[_tokenAddress]); // Token must be whitelisted first // Get the token uint tokensToReturn = 0; for (uint i =0; i<airdroppedTokens[_tokenAddress].length; i++){ TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][i]; if(msg.sender == ta.tokenOwner && airdropHasExpired(_tokenAddress,i)){ tokensToReturn = tokensToReturn.add(ta.tokenBalance); ta.tokenBalance = 0; } } E_TokensWithdrawn(_tokenAddress,msg.sender,tokensToReturn,now); } ///////////////////// // User functions ///////////////////// /** * @dev user can signup to the Airdrop Central to receive token airdrops * Airdrops made before the user registration won't be available to them. */ function signUpForAirdrops() public ifNotPaused{ require(signups[msg.sender].userAddress == address(0)); signups[msg.sender] = User(msg.sender,now); userSignupCount++; E_Signup(msg.sender,now); } /** * @dev removes user from airdrop list. * Beware that token distribution for existing airdrops won't change. * For example: if 100 tokens were to be distributed to 10 people (10 each). * if one quitted from the list, the other 9 will still get 10 each. * @notice WARNING: Quiting from the airdrop central will make you lose * tokens not yet withdrawn. Make sure to withdraw all pending tokens before * removing yourself from this list. Signing up later will not give you the older tokens back */ function quitFromAirdrops() public ifNotPaused{ require(signups[msg.sender].userAddress == msg.sender); delete signups[msg.sender]; userSignupCount--; } /** * @dev calculates the amount of tokens the user will be able to withdraw * Given a token address, the function checks all airdrops with the same address * @param _tokenAddress is the token the user wants to check his balance for * @return totalTokensAvailable is the tokens calculated */ function getTokensAvailableToMe(address _tokenAddress) view public returns (uint){ require(tokenWhitelist[_tokenAddress]); // Token must be whitelisted first // Get User instance, given the sender account User storage user = signups[msg.sender]; require(user.userAddress != address(0)); uint totalTokensAvailable= 0; for (uint i =0; i<airdroppedTokens[_tokenAddress].length; i++){ TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][i]; uint _withdrawnBalance = user.withdrawnBalances[_tokenAddress][i]; //Check that user signed up before the airdrop was done. If so, he is entitled to the tokens //And the airdrop must not have expired if(ta.airdropDate >= user.signupDate && now <= ta.airdropExpirationDate){ // The user will get a portion of the total tokens airdroped, // divided by the users at the moment the airdrop was created uint tokensAvailable = ta.totalDropped.div(ta.usersAtDate); // if the user has not alreay withdrawn the tokens, count them if(_withdrawnBalance < tokensAvailable){ totalTokensAvailable = totalTokensAvailable.add(tokensAvailable); } } } return totalTokensAvailable; } /** * @dev calculates and withdraws the amount of tokens the user has been awarded by airdrops * Given a token address, the function checks all airdrops with the same * address and withdraws the corresponding tokens for the user. * @param _tokenAddress is the token the user wants to check his balance for */ function withdrawTokens(address _tokenAddress) ifNotPaused public { require(tokenWhitelist[_tokenAddress]); // Token must be whitelisted first // Get User instance, given the sender account User storage user = signups[msg.sender]; require(user.userAddress != address(0)); uint totalTokensToTransfer = 0; // For each airdrop made for this token (token owner may have done several airdrops at any given point) for (uint i =0; i<airdroppedTokens[_tokenAddress].length; i++){ TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][i]; uint _withdrawnBalance = user.withdrawnBalances[_tokenAddress][i]; //Check that user signed up before the airdrop was done. If so, he is entitled to the tokens //And the airdrop must not have expired if(ta.airdropDate >= user.signupDate && now <= ta.airdropExpirationDate){ // The user will get a portion of the total tokens airdroped, // divided by the users at the moment the airdrop was created uint tokensToTransfer = ta.totalDropped.div(ta.usersAtDate); // if the user has not alreay withdrawn the tokens if(_withdrawnBalance < tokensToTransfer){ // Register the tokens withdrawn by the user and total tokens withdrawn user.withdrawnBalances[_tokenAddress][i] = tokensToTransfer; ta.tokenBalance = ta.tokenBalance.sub(tokensToTransfer); totalTokensToTransfer = totalTokensToTransfer.add(tokensToTransfer); } } } E_TokensWithdrawn(_tokenAddress,msg.sender,totalTokensToTransfer,now); } function airdropsCount() public view returns (uint){ return airdrops.length; } function getAddress() public view returns (address){ return address(this); } function airdropHasExpired(address _tokenAddress, uint _id) public view returns (bool){ TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][_id]; return (now > ta.airdropExpirationDate); } }
Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
function TokenERC20( ) public { }
1,363,789
pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; struct VestingWallet { address wallet; uint256 totalAmount; uint256 dayAmount; uint256 startDay; uint256 afterDays; bool nonlinear; bool advisory; } /** * dailyRate: the daily amount of tokens to give access to, * this is a percentage * 1000000000000000000 * this value is ignored if nonlinear is true * afterDays: vesting cliff, dont allow any withdrawal before these days expired * nonlinear: non linear vesting, used for PRIVATE/FOUNDATION/STRATEGIC sales **/ struct VestingType { uint256 dailyRate; uint256 afterDays; bool nonlinear; bool advisory; } import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract PNLToken is Ownable, ERC20Burnable { using SafeMath for uint256; mapping(address => VestingWallet) public vestingWallets; VestingType[] public vestingTypes; mapping(address => bool) public freezeList; uint256 public constant PRECISION = 1e18; uint256 public constant ONE_HUNDRED_PERCENT = PRECISION * 100; // Non linear unlocks [i,j] j% per day for i days uint256[][] public nonLinearUnlock = [ [10000000000000000000, 1], //10% during the first day [1000000000000000000, 40], //1% for the next 40 days [250000000000000000, 200] // then 0.25% per 200 days ]; uint256[][] public advisoryNonLinearUnlock = [ [uint256(20000000000000000000), 1], //20% during the first day [uint256(666666666666666666), 121] //0,66% daily after ]; /** * Setup the initial supply and types of vesting schemas **/ constructor() ERC20("PNLToken", "PNL") { // 0: TEAM, 2.7% monthly (0.09% daily) 1 year after TGE. vestingTypes.push( VestingType(92592592000000000, 360 days, false, false) ); // 1: MARKETING, 3% monthly (0.1% daily) after TGE. vestingTypes.push(VestingType(100000000000000000, 0, false, false)); // 2: SEED/PRIVATE/STRATEGIC NONLINEAR 10% at TGE, then 1% daily over 40 days, then 0.25% for 200 days. vestingTypes.push(VestingType(0, 0, true, false)); // 3: ADVISORY. 20% at TGE, then 0,67% daily over 120 days vestingTypes.push(VestingType(0, 0, true, true)); // 4: Immediate unlock vestingTypes.push(VestingType(100000000000000000000, 0, false, false)); // 5: FOUNDATION. 5% monthly (0.166% daily) 1 year after TGE. vestingTypes.push( VestingType(166666666666666666, 360 days, false, false) ); // 6: STACKING. 4.17% monthly (0.139% daily) after TGE vestingTypes.push(VestingType(138888888888888888, 0, false, false)); // Release BEFORE token start, tokens for liquidity _mint(address(0xB1537209C77C42d5fe33B56FD2bA3a7434c5Acb8), 1500000e18); // and public sale _mint(address(0xB1537209C77C42d5fe33B56FD2bA3a7434c5Acb8), 3400000e18); } // Vested tokens wont be available before the listing time function getListingTime() public pure returns (uint256) { return 1621357200; } function getMaxTotalSupply() public pure returns (uint256) { return PRECISION * 1e8; // 100 million tokens with 18 decimals } function mulDiv( uint256 x, uint256 y, uint256 z ) private pure returns (uint256) { return x.mul(y).div(z); } function freeze(address user) external onlyOwner { freezeList[user] = true; } function unfreeze(address user) external onlyOwner { freezeList[user] = false; } function addAllocations( address[] memory addresses, uint256[] memory totalAmounts, uint256 vestingTypeIndex ) external onlyOwner returns (bool) { require( addresses.length == totalAmounts.length, "Address and totalAmounts length must be same" ); require( vestingTypeIndex < vestingTypes.length, "Vesting type isnt found" ); VestingType memory vestingType = vestingTypes[vestingTypeIndex]; uint256 addressesLength = addresses.length; for (uint256 i = 0; i < addressesLength; i++) { address _address = addresses[i]; uint256 totalAmount = totalAmounts[i]; // We add 1 to round up, this prevents small amounts from never vesting uint256 dayAmount = mulDiv( totalAmounts[i], vestingType.dailyRate, ONE_HUNDRED_PERCENT ); uint256 afterDay = vestingType.afterDays; bool nonlinear = vestingType.nonlinear; bool advisory = vestingType.advisory; addVestingWallet( _address, totalAmount, dayAmount, afterDay, nonlinear, advisory ); } return true; } function _mint(address account, uint256 amount) internal override { uint256 totalSupply = super.totalSupply(); require( getMaxTotalSupply() >= totalSupply.add(amount), "Maximum supply exceeded!" ); super._mint(account, amount); } function addVestingWallet( address wallet, uint256 totalAmount, uint256 dayAmount, uint256 afterDays, bool nonlinear, bool advisory ) internal { require( vestingWallets[wallet].totalAmount == 0, "Vesting wallet already created for this address" ); uint256 releaseTime = getListingTime(); // Create vesting wallets VestingWallet memory vestingWallet = VestingWallet( wallet, totalAmount, dayAmount, releaseTime.add(afterDays), afterDays, nonlinear, advisory ); vestingWallets[wallet] = vestingWallet; _mint(wallet, totalAmount); } function getTimestamp() external view returns (uint256) { return block.timestamp; } /** * Returns the amount of days passed with vesting */ function getDays(uint256 afterDays) public view returns (uint256) { uint256 releaseTime = getListingTime(); uint256 time = releaseTime.add(afterDays); if (block.timestamp < time) { return 0; } uint256 diff = block.timestamp.sub(time); uint256 ds = diff.div(1 days).add(1); return ds; } function isStarted(uint256 startDay) public view returns (bool) { uint256 releaseTime = getListingTime(); if (block.timestamp < releaseTime || block.timestamp < startDay) { return false; } return true; } // Calculate the amount of unlocked tokens after X days for a given amount, nonlinear function calculateNonLinear(uint256 _days, uint256 amount) public view returns (uint256) { if (_days > 360) { return amount; } uint256 unlocked = 0; uint256 _days_remainder = 0; for (uint256 i = 0; i < nonLinearUnlock.length; i++) { if (_days <= _days_remainder) break; if (_days.sub(_days_remainder) >= nonLinearUnlock[i][1]) { unlocked = unlocked.add( mulDiv(amount, nonLinearUnlock[i][0], ONE_HUNDRED_PERCENT) .mul(nonLinearUnlock[i][1]) ); } if (_days.sub(_days_remainder) < nonLinearUnlock[i][1]) { unlocked = unlocked.add( mulDiv(amount, nonLinearUnlock[i][0], ONE_HUNDRED_PERCENT) .mul(_days.sub(_days_remainder)) ); } _days_remainder += nonLinearUnlock[i][1]; } if (unlocked > amount) { unlocked = amount; } return unlocked; } function calculateNonLinearAdvisory(uint256 _days, uint256 amount) public view returns (uint256) { if (_days > 360) { return amount; } uint256 unlocked = 0; uint256 _days_remainder = 0; for (uint256 i = 0; i < advisoryNonLinearUnlock.length; i++) { if (_days <= _days_remainder) break; if (_days.sub(_days_remainder) >= advisoryNonLinearUnlock[i][1]) { unlocked = unlocked.add( mulDiv( amount, advisoryNonLinearUnlock[i][0], ONE_HUNDRED_PERCENT ) .mul(advisoryNonLinearUnlock[i][1]) ); } if (_days.sub(_days_remainder) < advisoryNonLinearUnlock[i][1]) { unlocked = unlocked.add( mulDiv( amount, advisoryNonLinearUnlock[i][0], ONE_HUNDRED_PERCENT ) .mul(_days.sub(_days_remainder)) ); } _days_remainder += advisoryNonLinearUnlock[i][1]; } if (unlocked > amount) { unlocked = amount; } return unlocked; } // Returns the amount of tokens unlocked by vesting so far function getUnlockedVestingAmount(address sender) public view returns (uint256) { if (vestingWallets[sender].totalAmount == 0) { return 0; } if (!isStarted(0)) { return 0; } uint256 dailyTransferableAmount = 0; uint256 trueDays = getDays(vestingWallets[sender].afterDays); if (vestingWallets[sender].nonlinear == true) { if (vestingWallets[sender].advisory == false) { dailyTransferableAmount = calculateNonLinear( trueDays, vestingWallets[sender].totalAmount ); } else { dailyTransferableAmount = calculateNonLinearAdvisory( trueDays, vestingWallets[sender].totalAmount ); } } else { dailyTransferableAmount = vestingWallets[sender].dayAmount.mul( trueDays ); } if (dailyTransferableAmount > vestingWallets[sender].totalAmount) { return vestingWallets[sender].totalAmount; } return dailyTransferableAmount; } // Returns the amount of vesting tokens still locked function getRestAmount(address sender) public view returns (uint256) { uint256 transferableAmount = getUnlockedVestingAmount(sender); uint256 restAmount = vestingWallets[sender].totalAmount.sub(transferableAmount); return restAmount; } function isFrozen(address sender) public view returns (bool) { if (freezeList[sender] == true) return false; return true; } // Transfer control function canTransfer(address sender, uint256 amount) public view returns (bool) { // Treat as a normal coin if this is not a vested wallet if (vestingWallets[sender].totalAmount == 0) { return true; } uint256 balance = balanceOf(sender); uint256 restAmount = getRestAmount(sender); // Account for sending received tokens outside of the vesting schedule if ( balance > vestingWallets[sender].totalAmount && balance.sub(vestingWallets[sender].totalAmount) >= amount ) { return true; } // Don't allow vesting if the period has not started yet or if you are below allowance if ( !isStarted(vestingWallets[sender].startDay) || balance.sub(amount) < restAmount ) { return false; } return true; } // @override function _beforeTokenTransfer( address sender, address recipient, uint256 amount ) internal virtual override(ERC20) { // Reject any transfers that are not allowed require(isFrozen(sender), "The account is frozen"); require( canTransfer(sender, amount), "Unable to transfer, not unlocked yet." ); super._beforeTokenTransfer(sender, recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual 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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // 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: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // 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 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); }
Create vesting wallets
function addVestingWallet( address wallet, uint256 totalAmount, uint256 dayAmount, uint256 afterDays, bool nonlinear, bool advisory ) internal { require( vestingWallets[wallet].totalAmount == 0, "Vesting wallet already created for this address" ); uint256 releaseTime = getListingTime(); VestingWallet memory vestingWallet = VestingWallet( wallet, totalAmount, dayAmount, releaseTime.add(afterDays), afterDays, nonlinear, advisory ); vestingWallets[wallet] = vestingWallet; _mint(wallet, totalAmount); }
11,930,376
pragma solidity 0.4.24; import "./Authorizable.sol"; import "./EightExToken.sol"; import "./base/math/SafeMath.sol"; /** @title Stake Contract - Processors stake tokens to claim transactions */ /** @author Kerman Kohli - <kerman@8xprotocol.com> */ contract StakeContract is Authorizable { using SafeMath for uint; struct Stake { uint lockedUp; uint total; } struct TokenStake { uint lockedUp; uint total; } mapping (address => mapping (address => Stake)) public userStakes; mapping (address => TokenStake) tokenStakes; EightExToken public tokenContract; event Locked(address indexed staker, address indexed tokenAddress, uint indexed amount); event Unlocked(address indexed staker, address indexed tokenAddress, uint indexed amount); event Slashed(address indexed staker, address indexed tokenAddress, uint indexed amount); event Transferred(address indexed staker, address indexed tokenAddress, uint indexed amount, address destination); event ToppedUp(address indexed staker, address indexed tokenAddress, uint indexed amount); event Withdrew(address indexed staker, address indexed tokenAddress, uint indexed amount); /** * PUBLIC FUNCTIONS */ constructor(address _tokenAddress) public { tokenContract = EightExToken(_tokenAddress); } /** @dev When the processor claims a transaction their tokens are staked. * @param _staker is the processors who is staking thier tokens. * @param _tokenAddress token for which to stake for. * @param _amount is how much they would like to stake; */ function lockTokens(address _staker, address _tokenAddress, uint _amount) public onlyAuthorized { require(getAvailableStake(_staker, _tokenAddress) >= _amount); userStakes[_staker][_tokenAddress].lockedUp += _amount; tokenStakes[_tokenAddress].lockedUp += _amount; emit Locked(_staker, _tokenAddress, _amount); } /** @dev When a processor executes a transaction their tokens are unstaked. * @param _staker is the processors who is staking thier tokens. * @param _tokenAddress token for which to stake for. * @param _amount is how much they would like to unstake; */ function unlockTokens(address _staker, address _tokenAddress, uint _amount) public onlyAuthorized { // Ensure that they can't unstake more than they actually have require(userStakes[_staker][_tokenAddress].lockedUp >= _amount); userStakes[_staker][_tokenAddress].lockedUp -= _amount; tokenStakes[_tokenAddress].lockedUp -= _amount; emit Unlocked(_staker, _tokenAddress, _amount); } /** @dev When the processor doesn't execute a transaction they claimed * their tokens are slashed. * @param _staker is the processors who's tokens need to be slashed. * @param _tokenAddress token for which to stake for. * @param _amount is how many tokens need to be slashed. */ function slashTokens(address _staker, address _tokenAddress, uint _amount) public onlyAuthorized { // Make sure that an authorized address can't slash more tokens than // they actually have locked up. require(userStakes[_staker][_tokenAddress].lockedUp >= _amount); // Reduce the total amount first userStakes[_staker][_tokenAddress].total -= _amount; userStakes[_staker][_tokenAddress].lockedUp -= _amount; tokenStakes[_tokenAddress].total -= _amount; tokenStakes[_tokenAddress].lockedUp -= _amount; emit Slashed(_staker, _tokenAddress, _amount); } /** @dev When someone catches out another user for not processing * their tokens are transferred to them. * @param _staker is the processors who's tokens need to be slashed. * @param _tokenAddress token for which to stake for. * @param _amount is how many tokens need to be slashed. * @param _destination is the person to transfer the stake to. */ function transferStake(address _staker, address _tokenAddress, uint _amount, address _destination) public onlyAuthorized { // Make sure that an authorized address can't slash more tokens than // they actually have locked up. require(userStakes[_staker][_tokenAddress].lockedUp >= _amount); // Reduce the total amount first userStakes[_staker][_tokenAddress].total -= _amount; userStakes[_staker][_tokenAddress].lockedUp -= _amount; // Transfer the stake userStakes[_destination][_tokenAddress].total += _amount; tokenStakes[_tokenAddress].lockedUp -= _amount; // Total is constant, only locked up decreases. emit Transferred(_staker, _tokenAddress, _amount, _destination); } /** @dev Check how many tokens the processor has in total at this moment. * @param _staker is the processor address. * @param _tokenAddress token for which to stake for. */ function getTotalStake(address _staker, address _tokenAddress) public view returns (uint total) { return userStakes[_staker][_tokenAddress].total; } /** @dev Check how many tokens the processor has available at this moment. * @param _staker is the processor address. * @param _tokenAddress token for which to stake for. */ function getAvailableStake(address _staker, address _tokenAddress) public view returns (uint available) { return (userStakes[_staker][_tokenAddress].total - userStakes[_staker][_tokenAddress].lockedUp); } /** @dev Check how many tokens the processor has locked at this moment. * @param _staker is the processor address. * @param _tokenAddress token for which to stake for. */ function getLockedStake(address _staker, address _tokenAddress) public view returns (uint locked) { return userStakes[_staker][_tokenAddress].lockedUp; } /** @dev Check how many staked tokens the currency has in total at this moment. * @param _tokenAddress token for which to stake for. */ function getTotalTokenStake(address _tokenAddress) public view returns (uint total) { return tokenStakes[_tokenAddress].total; } /** @dev Check how many tokens the currency has available at this moment. * @param _tokenAddress token for which to stake for. */ function getAvailableTokenStake(address _tokenAddress) public view returns (uint available) { return (tokenStakes[_tokenAddress].total - tokenStakes[_tokenAddress].lockedUp); } /** @dev Check how many tokens the currency has locked at this moment. * @param _tokenAddress token for which to stake for. */ function getLockedTokenStake(address _tokenAddress) public view returns (uint locked) { return tokenStakes[_tokenAddress].lockedUp; } /** @dev Top up your stake once you've given approval to transfer funds. * @param _amount is how much you would like to withdraw. * @param _tokenAddress token for which to stake for. */ function topUpStake(uint _amount, address _tokenAddress) public returns (bool success) { if (tokenContract.transferFrom(msg.sender, address(this), _amount)) { userStakes[msg.sender][_tokenAddress].total += _amount; tokenStakes[_tokenAddress].total += _amount; return true; } else { return false; } emit ToppedUp(msg.sender, _tokenAddress, _amount); } /** @dev Withdraw your stake from the stake contract. * @param _amount is how much you would like to withdraw. * @param _tokenAddress token for which to stake for. */ function withdrawStake(uint _amount, address _tokenAddress) public { // Check that they're not taking out more than they actually have. require(getAvailableStake(msg.sender, _tokenAddress) >= _amount); userStakes[msg.sender][_tokenAddress].total -= _amount; tokenStakes[_tokenAddress].total -= _amount; tokenContract.transfer(msg.sender, _amount); emit Withdrew(msg.sender, _tokenAddress, _amount); } }
When someone catches out another user for not processing their tokens are transferred to them. _staker is the processors who's tokens need to be slashed. _tokenAddress token for which to stake for. _amount is how many tokens need to be slashed. _destination is the person to transfer the stake to./ Make sure that an authorized address can't slash more tokens than they actually have locked up. Reduce the total amount first Transfer the stake
function transferStake(address _staker, address _tokenAddress, uint _amount, address _destination) public onlyAuthorized { require(userStakes[_staker][_tokenAddress].lockedUp >= _amount); userStakes[_staker][_tokenAddress].total -= _amount; userStakes[_staker][_tokenAddress].lockedUp -= _amount; userStakes[_destination][_tokenAddress].total += _amount; emit Transferred(_staker, _tokenAddress, _amount, _destination); }
7,328,120
/** *Submitted for verification at Etherscan.io on 2021-10-30 */ // 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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev 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() public view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev 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 ERC721URIStorage, 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(); } } /** * @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; } } /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract MetaVisa is ERC721Enumerable { using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; event Mint(address indexed from, address indexed to, uint256 indexed tokenId); mapping(address => bool) public isBuy; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor( string memory name, string memory symbol ) ERC721(name, symbol) { } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(string memory tokenURI) public virtual { // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. //getFeeAddress().transfer(msg.value); require(!isBuy[msg.sender], "mint:You can only buy it once "); uint256 tokenId = _tokenIdTracker.current(); _mint(msg.sender, _tokenIdTracker.current()); _setTokenURI(_tokenIdTracker.current(),tokenURI); _tokenIdTracker.increment(); isBuy[msg.sender]=true; emit Mint(address(0), msg.sender, tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override( ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override( ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI autogenerated based on the base URI passed at construction. See {ERC721-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./ We cannot just use balanceOf to create the new tokenId because tokens can be burned (destroyed), so we need a separate counter.getFeeAddress().transfer(msg.value);
function mint(string memory tokenURI) public virtual { require(!isBuy[msg.sender], "mint:You can only buy it once "); uint256 tokenId = _tokenIdTracker.current(); _mint(msg.sender, _tokenIdTracker.current()); _setTokenURI(_tokenIdTracker.current(),tokenURI); _tokenIdTracker.increment(); isBuy[msg.sender]=true; emit Mint(address(0), msg.sender, tokenId); }
10,029,877
pragma solidity ^0.8.0; // // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract BuidlBadges is ERC1155, Ownable, AccessControl { bytes32 public constant ADMINS_ROLE = keccak256("ADMIN"); uint256 public constant SIMPLE_NFT = 0; uint256 public constant STAKING = 1; uint256 public constant VENDOR = 2; uint256 public constant MULTI_SIG = 3; uint256 public constant ORACLES = 4; uint256 public constant EXCHANGE = 5; uint256 public constant BUYER_MINTS = 6; uint256 public constant STREAMS = 7; uint256 public constant DAMAGE_DEALER = 8; uint256 public constant COMMUNITY_HELPER = 9; event Minted(address recipient, uint256 tokenId); constructor(address[] memory admin) ERC1155( "https://forgottenbots.mypinata.cloud/ipfs/QmZvQZiZrTm2ewQXDUw1GA5eaGv7xnpzPRtaRZznFBmpoQ/{id}.json" ) { transferOwnership(0x34aA3F359A9D614239015126635CE7732c18fDF3); for (uint256 i = 0; i < admin.length; ++i) { _setupRole(DEFAULT_ADMIN_ROLE, admin[i]); } _setRoleAdmin(ADMINS_ROLE, DEFAULT_ADMIN_ROLE); } /** * @notice Mints the badge * @param tokenId identifies the badge to be minted (0-9 for now) */ function mint( address recipient, uint256 tokenId ) public { require(hasRole(ADMINS_ROLE, msg.sender), "admin only function"); _mint(msg.sender, tokenId, 1, ""); emit Minted(recipient, tokenId); } function reward(address recipient) public returns (uint256) { require(hasRole(ADMINS_ROLE, msg.sender), "admin only function"); _mint(recipient, DAMAGE_DEALER, 10**9, ""); } /** * @notice Allows original admins to add curators */ function addAdmins(address[] memory admins) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "DEFAULT_ADMIN only function"); for (uint256 i = 0; i < admins.length; ++i) { grantRole(ADMINS_ROLE, admins[i]); } } /** * @dev Contract uri */ function uri() public view returns (string memory) { return "https://forgottenbots.mypinata.cloud/ipfs/QmTYr3kBhyySATmt9UEgKBPgpg7DGRFL4wef9AoSsDxNo2"; } /** * @notice Block badge transfers */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155) { require(from == address(0) || to == address(0), "NonTransferrableERC1155Token: non transferrable"); super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } /** * @notice Block badge approvals, so they can't be listed on marketplaces. */ function setApprovalForAll( address operator, bool _approved ) public virtual override(ERC1155) { revert("NonApprovableERC1155Token: non-approvable"); } /** * @notice Override interface to use AccessControl */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC1155, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } }
Block badge approvals, so they can't be listed on marketplaces./
function setApprovalForAll( address operator, bool _approved ) public virtual override(ERC1155) { revert("NonApprovableERC1155Token: non-approvable"); }
2,481,173
/** *Submitted for verification at Etherscan.io on 2020-07-31 */ pragma solidity 0.6.12; // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return success Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return success Whether the approval was successful or not */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return success Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return remaining Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ReentrancyGuard { bool internal reentranceLock = false; /** * @dev Use this modifier on functions susceptible to reentrancy attacks */ modifier reentrancyGuard() { require(!reentranceLock, "Reentrant call detected!"); reentranceLock = true; // No no no, you naughty naughty! _; reentranceLock = false; } } pragma experimental ABIEncoderV2; /** * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) * @notice interface for StickerMarket */ interface StickerMarket { event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event MarketState(State state); event RegisterFee(uint256 value); event BurnRate(uint256 value); enum State { Invalid, Open, BuyOnly, Controlled, Closed } function state() external view returns(State); function snt() external view returns (address); function stickerPack() external view returns (address); function stickerType() external view returns (address); /** * @dev Mints NFT StickerPack in `_destination` account, and Transfers SNT using user allowance * emit NonfungibleToken.Transfer(`address(0)`, `_destination`, `tokenId`) * @notice buy a pack from market pack owner, including a StickerPack's token in `_destination` account with same metadata of `_packId` * @param _packId id of market pack * @param _destination owner of token being brought * @param _price agreed price * @return tokenId generated StickerPack token */ function buyToken( uint256 _packId, address _destination, uint256 _price ) external returns (uint256 tokenId); /** * @dev emits StickerMarket.Register(`packId`, `_urlHash`, `_price`, `_contenthash`) * @notice Registers to sell a sticker pack * @param _price cost in wei to users minting this pack * @param _donate value between 0-10000 representing percentage of `_price` that is donated to StickerMarket at every buy * @param _category listing category * @param _owner address of the beneficiary of buys * @param _contenthash EIP1577 pack contenthash for listings * @param _fee Fee msg.sender agrees to pay for this registration * @return packId Market position of Sticker Pack data. */ function registerPack( uint256 _price, uint256 _donate, bytes4[] calldata _category, address _owner, bytes calldata _contenthash, uint256 _fee ) external returns(uint256 packId); } /** * @dev ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed from, address indexed to, uint256 indexed value ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. * @return Total supply of NFTs. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } /** * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) * @notice interface for StickerType */ /* interface */ abstract contract StickerType is ERC721, ERC721Enumerable { // Interfaces can't inherit /** * @notice controller can generate packs at will * @param _price cost in wei to users minting with _urlHash metadata * @param _donate optional amount of `_price` that is donated to StickerMarket at every buy * @param _category listing category * @param _owner address of the beneficiary of buys * @param _contenthash EIP1577 pack contenthash for listings * @return packId Market position of Sticker Pack data. */ function generatePack( uint256 _price, uint256 _donate, bytes4[] calldata _category, address _owner, bytes calldata _contenthash ) external virtual returns(uint256 packId); /** * @notice removes all market data about a marketed pack, can only be called by market controller * @param _packId position to be deleted * @param _limit limit of categories to cleanup */ function purgePack(uint256 _packId, uint256 _limit) external virtual; /** * @notice changes contenthash of `_packId`, can only be called by controller * @param _packId which market position is being altered * @param _contenthash new contenthash */ function setPackContenthash(uint256 _packId, bytes calldata _contenthash) external virtual; /** * @notice This method can be used by the controller to extract mistakenly * sent tokens to this contract. * @param _token The address of the token contract that you want to recover * set to 0 in case you want to extract ether. */ function claimTokens(address _token) external virtual; /** * @notice changes price of `_packId`, can only be called when market is open * @param _packId pack id changing price settings * @param _price cost in wei to users minting this pack * @param _donate value between 0-10000 representing percentage of `_price` that is donated to StickerMarket at every buy */ function setPackPrice(uint256 _packId, uint256 _price, uint256 _donate) external virtual; /** * @notice add caregory in `_packId`, can only be called when market is open * @param _packId pack adding category * @param _category category to list */ function addPackCategory(uint256 _packId, bytes4 _category) external virtual; /** * @notice remove caregory in `_packId`, can only be called when market is open * @param _packId pack removing category * @param _category category to unlist */ function removePackCategory(uint256 _packId, bytes4 _category) external virtual; /** * @notice Changes if pack is enabled for sell * @param _packId position edit * @param _mintable true to enable sell */ function setPackState(uint256 _packId, bool _mintable) external virtual; /** * @notice read available market ids in a category (might be slow) * @param _category listing category * @return availableIds array of market id registered */ function getAvailablePacks(bytes4 _category) external virtual view returns (uint256[] memory availableIds); /** * @notice count total packs in a category * @param _category listing category * @return size total number of packs in category */ function getCategoryLength(bytes4 _category) external virtual view returns (uint256 size); /** * @notice read a packId in the category list at a specific index * @param _category listing category * @param _index index * @return packId on index */ function getCategoryPack(bytes4 _category, uint256 _index) external virtual view returns (uint256 packId); /** * @notice returns all data from pack in market * @param _packId pack id being queried * @return category list of categories registered to this packType * @return owner authorship holder * @return mintable new pack can be generated (rare tool) * @return timestamp registration timestamp * @return price current price * @return contenthash EIP1577 encoded hash */ function getPackData(uint256 _packId) external virtual view returns ( bytes4[] memory category, address owner, bool mintable, uint256 timestamp, uint256 price, bytes memory contenthash ); /** * @notice returns all data from pack in market * @param _packId pack id being queried * @return category list of categories registered to this packType * @return timestamp registration timestamp * @return contenthash EIP1577 encoded hash */ function getPackSummary(uint256 _packId) external virtual view returns ( bytes4[] memory category, uint256 timestamp, bytes memory contenthash ); /** * @notice returns payment data for migrated contract * @param _packId pack id being queried * @return owner authorship holder * @return mintable new pack can be generated (rare tool) * @return price current price * @return donate informational value between 0-10000 representing percentage of `price` that is donated to StickerMarket at every buy */ function getPaymentData(uint256 _packId) external virtual view returns ( address owner, bool mintable, uint256 price, uint256 donate ); } /** * @title SafeERC20 * @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol * and https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol */ contract SafeTransfer { function _safeTransfer(ERC20Token token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function _safeTransferFrom(ERC20Token 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(ERC20Token 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(_isContract(address(token)), "SafeTransfer: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeTransfer: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeTransfer: ERC20 operation did not succeed"); } } /** * @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); } } /** * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) * @notice Owner's backdoor withdrawal logic, used for code reuse. */ contract TokenWithdrawer is SafeTransfer { /** * @dev Withdraw all balance of each `_tokens` into `_destination`. * @param _tokens address of ERC20 token, or zero for withdrawing ETH. * @param _destination receiver of token */ function withdrawTokens( address[] memory _tokens, address payable _destination ) internal { uint len = _tokens.length; for(uint i = 0; i < len; i++){ withdrawToken(_tokens[i], _destination); } } /** * @dev Withdraw all balance of `_token` into `_destination`. * @param _token address of ERC20 token, or zero for withdrawing ETH. * @param _destination receiver of token */ function withdrawToken(address _token, address payable _destination) internal { uint256 balance; if (_token == address(0)) { balance = address(this).balance; (bool success, ) = _destination.call.value(balance)(""); require(success, "Transfer failed"); } else { ERC20Token token = ERC20Token(_token); balance = token.balanceOf(address(this)); _safeTransfer(token, _destination, balance); } } } /// @title Starterpack Distributor /// @notice Attempts to deliver 1 and only 1 starterpack containing ETH, ERC20 Tokens and NFT Stickerpacks to an eligible recipient /// @dev The contract assumes Signer has verified an In-App Purchase Receipt, only 1 pack per address is allowed, unless the owner calls clearPurchases() contract Distributor is SafeTransfer, ReentrancyGuard, TokenWithdrawer { address payable private owner; // Contract deployer can modify parameters address private signer; // Signer can only distribute Starterpacks // Defines the Starterpack parameters struct Pack { StickerMarket stickerMarket; // Sticker market contract for minting the sticker pack ids uint256 ethAmount; // The Amount of ETH to transfer to the recipient address[] tokens; // Array of ERC20 Contract Addresses uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[] uint256[] stickerPackIds; // Array of NFT's } Pack private defaultPack; Pack private promoPack; uint private promoAvailable; ERC20Token public sntToken; bool public pause = true; uint ineligibleVersion; mapping(bytes32 => bool) public ineligible; // Used to make addresses ineligible for subsequent starterpacks, after successful transaction event RequireApproval(address attribution); mapping(address => uint) public pendingAttributionCnt; mapping(address => uint) public attributionCnt; struct Attribution { bool enabled; uint256 ethAmount; // The Amount of ETH to transfer to the referrer address[] tokens; // Array of ERC20 Contract Addresses uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[] uint maxThreshold; } mapping(address => Attribution) defaultAttributionSettings; mapping(address => Attribution) promoAttributionSettings; // Modifiers -------------------------------------------------------------------------------------------- // Functions only Owner can call modifier onlyOwner { require(msg.sender == owner, "Unauthorized"); _; } // Logic ------------------------------------------------------------------------------------------------ /// @notice Check if an address is eligible for a starterpack /// @dev will return false if a transaction of distributePack for _recipient has been successfully executed /// @param _recipient The address to be checked for eligibility function eligible(address _recipient) public view returns (bool){ return !ineligible[keccak256(abi.encodePacked(ineligibleVersion, _recipient))]; } /// @notice Get the starter pack configuration /// @return stickerMarket address Stickermarket contract address /// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient /// @return tokens address[] List of tokens that will be sent to a recipient /// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient /// @return stickerPackIds uint[] List of sticker packs to send to a recipient function getDefaultPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds) { stickerMarket = address(defaultPack.stickerMarket); ethAmount = defaultPack.ethAmount; tokens = defaultPack.tokens; tokenAmounts = defaultPack.tokenAmounts; stickerPackIds = defaultPack.stickerPackIds; } /// @notice Get the promo pack configuration /// @return stickerMarket address Stickermarket contract address /// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient /// @return tokens address[] List of tokens that will be sent to a recipient /// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient /// @return stickerPackIds uint[] List of sticker packs to send to a recipient /// @return available uint number of promo packs available function getPromoPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds, uint256 available) { stickerMarket = address(promoPack.stickerMarket); ethAmount = promoPack.ethAmount; tokens = promoPack.tokens; tokenAmounts = promoPack.tokenAmounts; stickerPackIds = promoPack.stickerPackIds; available = promoAvailable; } event Distributed(address indexed recipient, address indexed attribution); /// @notice Distributes a starterpack to an eligible address. Either a promo pack or a default will be distributed depending on availability /// @dev Can only be called by signer, assumes signer has validated an IAP receipt, owner can block calling by pausing. /// @param _recipient A payable address that is sent a starterpack after being checked for eligibility /// @param _attribution A payable address who referred the starterpack purchaser function distributePack(address payable _recipient, address payable _attribution) external reentrancyGuard { require(!pause, "Paused"); require(msg.sender == signer, "Unauthorized"); require(eligible(_recipient), "Recipient is not eligible."); require(_recipient != _attribution, "Recipient should be different from Attribution address"); Pack memory pack; if(promoAvailable > 0){ pack = promoPack; promoAvailable--; } else { pack = defaultPack; } // Transfer Tokens // Iterate over tokens[] and transfer the an amount corresponding to the i cell in tokenAmounts[] for (uint256 i = 0; i < pack.tokens.length; i++) { ERC20Token token = ERC20Token(pack.tokens[i]); uint256 amount = pack.tokenAmounts[i]; _safeTransfer(token, _recipient, amount); } // NFT Sticker Packs StickerType stickerType = StickerType(pack.stickerMarket.stickerType()); for (uint256 i = 0; i < pack.stickerPackIds.length; i++) { uint256 packId = pack.stickerPackIds[i]; (, bool mintable, uint256 price,) = stickerType.getPaymentData(packId); if(mintable && price > 0){ sntToken.approve(address(pack.stickerMarket),price); pack.stickerMarket.buyToken( packId, _recipient, price ); } } // The recipient is no longer eligible for a pack, unless clearPurchases is called. ineligible[keccak256(abi.encodePacked(ineligibleVersion, _recipient))] = true; // Transfer ETH // .transfer bad post Istanbul fork :| (bool success, ) = _recipient.call.value(pack.ethAmount)(""); require(success, "ETH Transfer failed"); emit Distributed(_recipient, _attribution); if (_attribution == address(0)) return; // Determine if attribution is valid bool isPromo; Attribution memory attr; if(promoAttributionSettings[_attribution].maxThreshold > 0){ isPromo = true; promoAttributionSettings[_attribution].maxThreshold--; attr = promoAttributionSettings[_attribution]; } else { attr = defaultAttributionSettings[_attribution]; } if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } if(!isPromo && (attributionCnt[_attribution] + 1) > attr.maxThreshold){ emit RequireApproval(_attribution); pendingAttributionCnt[_attribution]++; } else { if(!isPromo){ attributionCnt[_attribution]++; } if (attr.ethAmount != 0){ (bool success, ) = _attribution.call.value(attr.ethAmount)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i]; _safeTransfer(token, _attribution, amount); } } } function _payPendingAttributions(address _attribOwner, Attribution memory attr) internal { uint pendingAttributions = pendingAttributionCnt[_attribOwner]; if (address(this).balance == 0) return; //inject FORCED TO RECEIVE ETHERS if (attr.maxThreshold < attributionCnt[_attribOwner] + pendingAttributions) return; uint totalETHToPay = pendingAttributions * attr.ethAmount; attributionCnt[_attribOwner] += pendingAttributions; pendingAttributionCnt[_attribOwner] = 0; if (totalETHToPay != 0){ (bool success, ) = _attribOwner.call.value(totalETHToPay)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i] * pendingAttributions; _safeTransfer(token, _attribOwner, amount); } } /// @notice Get rewards for specific referrer /// @param _account The address to obtain the attribution config /// @param _isPromo Indicates if the configuration for a promo should be returned or not /// @return ethAmount Amount of ETH in wei /// @return tokenLen Number of tokens configured as part of the reward /// @return maxThreshold If isPromo == true: Number of promo bonuses still available for that address else: Max number of attributions to pay before requiring approval /// @return attribCount Number of referrals function getReferralReward(address _account, bool _isPromo) public view returns (uint ethAmount, uint tokenLen, uint maxThreshold, uint attribCount) { Attribution memory attr; if(_isPromo){ attr = promoAttributionSettings[_account]; } else { attr = defaultAttributionSettings[_account]; if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } } ethAmount = attr.ethAmount; maxThreshold = attr.maxThreshold; attribCount = attributionCnt[_account]; tokenLen = attr.tokens.length; } /// @notice Get token rewards for specific address /// @param _account The address to obtain the attribution's token config /// @param _isPromo Indicates if the configuration for a promo should be returned or not /// @param _idx Index of token array in the attribution used to obtain the token config /// @return token ERC20 contract address /// @return tokenAmount Amount of token configured in the attribution function getReferralRewardTokens(address _account, bool _isPromo, uint _idx) public view returns (address token, uint tokenAmount) { Attribution memory attr; if(_isPromo){ attr = promoAttributionSettings[_account]; } else { attr = defaultAttributionSettings[_account]; if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } } token = attr.tokens[_idx]; tokenAmount = attr.tokenAmounts[_idx]; } fallback() external payable { // ... } // Admin ------------------------------------------------------------------------------------------------ /// @notice Allows the Owner to allow or prohibit Signer from calling distributePack(). /// @dev setPause must be called before Signer can call distributePack() function setPause(bool _pause) external onlyOwner { pause = _pause; } /// @notice Allows the owner to clear the purchase history. Recipients will be able to receive a starter pack again function clearPurchases() external onlyOwner { ineligibleVersion++; } /// @notice Set a starter pack configuration /// @dev The Owner can change the default starterpack contents /// @param _newPack starter pack configuration function changeStarterPack(Pack memory _newPack) public onlyOwner { require(_newPack.tokens.length == _newPack.tokenAmounts.length, "Mismatch with Tokens & Amounts"); for (uint256 i = 0; i < _newPack.tokens.length; i++) { require(_newPack.tokenAmounts[i] > 0, "Amounts must be non-zero"); } defaultPack = _newPack; sntToken = ERC20Token(defaultPack.stickerMarket.snt()); } /// @notice Set a promo configuration /// @dev The Owner can change the promo pack contents /// @param _newPromoPack Promo pack configuration /// @param _numberOfPacks Max number of promo packs to be given before using the default config function changePromoPack(Pack memory _newPromoPack, uint _numberOfPacks) public onlyOwner { require(_newPromoPack.tokens.length == _newPromoPack.tokenAmounts.length, "Mismatch with Tokens & Amounts"); for (uint256 i = 0; i < _newPromoPack.tokens.length; i++) { require(_newPromoPack.tokenAmounts[i] > 0, "Amounts must be non-zero"); } promoPack = _newPromoPack; promoAvailable = _numberOfPacks; } /// @notice Safety function allowing the owner to immediately pause starterpack distribution and withdraw all balances in the the contract function withdraw(address[] calldata _tokens) external onlyOwner { pause = true; withdrawTokens(_tokens, owner); } /// @notice Changes the Signer of the contract /// @param _newSigner The new Signer of the contract function changeSigner(address _newSigner) public onlyOwner { require(_newSigner != address(0), "zero_address not allowed"); signer = _newSigner; } /// @notice Changes the owner of the contract /// @param _newOwner The new owner of the contract function changeOwner(address payable _newOwner) external onlyOwner { require(_newOwner != address(0), "zero_address not allowed"); owner = _newOwner; } /// @notice Set default/custom payout and threshold for referrals /// @param _isPromo indicates if this attribution config is a promo or default config /// @param _ethAmount Payout for referrals /// @param _thresholds Max number of referrals allowed beforee requiring approval /// @param _assignedTo Use a valid address here to set custom settings. To set the default payout and threshold, use address(0); function setPayoutAndThreshold( bool _isPromo, uint256 _ethAmount, address[] calldata _tokens, uint256[] calldata _tokenAmounts, uint256[] calldata _thresholds, address[] calldata _assignedTo ) external onlyOwner { require(_thresholds.length == _assignedTo.length, "Array length mismatch"); require(_tokens.length == _tokenAmounts.length, "Array length mismatch"); for (uint256 i = 0; i < _thresholds.length; i++) { bool enabled = _assignedTo[i] != address(0); Attribution memory attr = Attribution({ enabled: enabled, ethAmount: _ethAmount, maxThreshold: _thresholds[i], tokens: _tokens, tokenAmounts: _tokenAmounts }); if(_isPromo){ promoAttributionSettings[_assignedTo[i]] = attr; } else { if(enabled){ _payPendingAttributions(_assignedTo[i], attr); } defaultAttributionSettings[_assignedTo[i]] = attr; } } } /// @notice Remove attribution configuration for addresses /// @param _assignedTo Array of addresses with an attribution configured /// @param _isPromo Indicates if the configuration to delete is the promo or default function removePayoutAndThreshold(address[] calldata _assignedTo, bool _isPromo) external onlyOwner { if (_isPromo) { for (uint256 i = 0; i < _assignedTo.length; i++) { delete promoAttributionSettings[_assignedTo[i]]; } } else { for (uint256 i = 0; i < _assignedTo.length; i++) { delete defaultAttributionSettings[_assignedTo[i]]; } } } /// @param _signer allows the contract deployer(owner) to define the signer on construction constructor(address _signer) public { require(_signer != address(0), "zero_address not allowed"); owner = msg.sender; signer = _signer; } }
Distributes a starterpack to an eligible address. Either a promo pack or a default will be distributed depending on availability Can only be called by signer, assumes signer has validated an IAP receipt, owner can block calling by pausing. _recipient A payable address that is sent a starterpack after being checked for eligibility _attribution A payable address who referred the starterpack purchaser Transfer Tokens Iterate over tokens[] and transfer the an amount corresponding to the i cell in tokenAmounts[]
function distributePack(address payable _recipient, address payable _attribution) external reentrancyGuard { require(!pause, "Paused"); require(msg.sender == signer, "Unauthorized"); require(eligible(_recipient), "Recipient is not eligible."); require(_recipient != _attribution, "Recipient should be different from Attribution address"); Pack memory pack; if(promoAvailable > 0){ pack = promoPack; promoAvailable--; pack = defaultPack; } for (uint256 i = 0; i < pack.tokens.length; i++) { ERC20Token token = ERC20Token(pack.tokens[i]); uint256 amount = pack.tokenAmounts[i]; _safeTransfer(token, _recipient, amount); } for (uint256 i = 0; i < pack.stickerPackIds.length; i++) { uint256 packId = pack.stickerPackIds[i]; (, bool mintable, uint256 price,) = stickerType.getPaymentData(packId); if(mintable && price > 0){ sntToken.approve(address(pack.stickerMarket),price); pack.stickerMarket.buyToken( packId, _recipient, price ); } } require(success, "ETH Transfer failed"); emit Distributed(_recipient, _attribution); if (_attribution == address(0)) return; bool isPromo; Attribution memory attr; if(promoAttributionSettings[_attribution].maxThreshold > 0){ isPromo = true; promoAttributionSettings[_attribution].maxThreshold--; attr = promoAttributionSettings[_attribution]; attr = defaultAttributionSettings[_attribution]; } if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } if(!isPromo && (attributionCnt[_attribution] + 1) > attr.maxThreshold){ emit RequireApproval(_attribution); pendingAttributionCnt[_attribution]++; if(!isPromo){ attributionCnt[_attribution]++; } if (attr.ethAmount != 0){ (bool success, ) = _attribution.call.value(attr.ethAmount)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i]; _safeTransfer(token, _attribution, amount); } } }
994,067
./full_match/80001/0x897aE1577245E65741F94417d2633C00F155eb5F/sources/contracts/RecruitmentATSSmartContract.sol
Function to add an applicant Ensure the applicant does not already exist Add the applicant Emit a NewApplicantAdded event
function addApplicant( string memory name, uint age, string memory resumeHash, string memory emailAddress, address ethAddressIn ) public { require(applicants[ethAddressIn].age == 0, 'Applicant already exists.'); applicants[ethAddressIn] = Applicant( name, age, resumeHash, ethAddressIn, emailAddress ); applicantByEmail[emailAddress] = Applicant( name, age, resumeHash, ethAddressIn, emailAddress ); emit NewApplicantAdded(msg.sender, name, age, resumeHash); }
5,565,355
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {Ownable} from "openzeppelin/contracts/access/Ownable.sol"; struct BatchConfig { uint64 startBatchIndex; // the index of the first batch using this config uint64 startBlockNumber; // the block number from which on this config is applicable address[] keypers; // the keyper addresses uint64 threshold; // the threshold parameter uint64 batchSpan; // the duration of one batch in blocks uint64 batchSizeLimit; // the maximum size of a batch in bytes uint64 transactionSizeLimit; // the maximum size of each transaction in the batch in bytes uint64 transactionGasLimit; // the maximum amount of gas each transaction may use address feeReceiver; // the address receiving the collected fees address targetAddress; // the address of the contract responsible of executing transactions bytes4 targetFunctionSelector; // function of the target contract that executes transactions uint64 executionTimeout; // the number of blocks after which execution can be skipped } /// @title A contract that manages `BatchConfig` objects. /// @dev The config objects are stored in sequence, with configs applicable to later batches being /// lined up behind configs applicable to earlier batches (according to /// `config.startBlockNumber`). The contract owner is entitled to add or remove configs at the /// end at will as long as a notice of at least `configChangeHeadsUpBlocks` is given. /// @dev To add a new config, first populate the `nextConfig` object accordingly and then schedule /// it with `scheduleNextConfig`. contract ConfigContract is Ownable { /// @notice The event emitted after a new config object has been scheduled. /// @param numConfigs The new number of configs stored. event ConfigScheduled(uint64 numConfigs); /// @notice The event emitted after the owner has unscheduled one or more config objects. /// @param numConfigs The new number of configs stored. event ConfigUnscheduled(uint64 numConfigs); // Stores all scheduled configs, plus the next config at the end BatchConfig[] private configs; uint64 public immutable configChangeHeadsUpBlocks; constructor(uint64 headsUp) { configs.push(_zeroConfig()); // guard configs.push(_zeroConfig()); // next config configChangeHeadsUpBlocks = headsUp; } function _zeroConfig() internal pure returns (BatchConfig memory) { return BatchConfig({ startBatchIndex: 0, startBlockNumber: 0, keypers: new address[](0), threshold: 0, batchSpan: 0, batchSizeLimit: 0, transactionSizeLimit: 0, transactionGasLimit: 0, feeReceiver: address(0), targetAddress: address(0), targetFunctionSelector: bytes4(0), executionTimeout: 0 }); } function numConfigs() public view returns (uint64) { return uint64(configs.length) - 1; // exclude next config } function nextConfigIndex() public view returns (uint64) { return uint64(configs.length) - 1; } function nextConfig() public view returns (BatchConfig memory) { return configs[nextConfigIndex()]; } function lastScheduledConfigIndex() public view returns (uint64) { return uint64(configs.length) - 2; } function lastScheduledConfig() public view returns (BatchConfig memory) { return configs[lastScheduledConfigIndex()]; } /// @notice Get the index of the config for the batch with the given index. /// @param batchIndex The index of the batch. function configIndexForBatchIndex(uint64 batchIndex) public view returns (uint64) { for (uint256 i = configs.length - 2; i >= 0; i--) { if (configs[i].startBatchIndex <= batchIndex) { return uint64(i); } } assert(false); return 0; // only for the linter } /// @notice Get the config for a certain batch. /// @param batchIndex The index of the batch. function configForBatchIndex(uint64 batchIndex) public view returns (BatchConfig memory) { uint64 configIndex = configIndexForBatchIndex(batchIndex); return configs[configIndex]; } function configForConfigIndex(uint64 configIndex) public view returns (BatchConfig memory) { return configs[configIndex]; } // // Config field getters // function configKeypers(uint64 configIndex, uint64 keyperIndex) public view returns (address) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].keypers[keyperIndex]; } function configNumKeypers(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return uint64(configs[configIndex].keypers.length); } function configStartBatchIndex(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].startBatchIndex; } function configStartBlockNumber(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].startBlockNumber; } function configThreshold(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].threshold; } function configBatchSpan(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].batchSpan; } function configBatchSizeLimit(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].batchSizeLimit; } function configTransactionSizeLimit(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].transactionSizeLimit; } function configTransactionGasLimit(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].transactionGasLimit; } function configFeeReceiver(uint64 configIndex) public view returns (address) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].feeReceiver; } function configTargetAddress(uint64 configIndex) public view returns (address) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].targetAddress; } function configTargetFunctionSelector(uint64 configIndex) public view returns (bytes4) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].targetFunctionSelector; } function configExecutionTimeout(uint64 configIndex) public view returns (uint64) { require( configIndex < numConfigs(), "ConfigContract: config index out of range" ); return configs[configIndex].executionTimeout; } // // next config setters // function nextConfigSetStartBatchIndex(uint64 startBatchIndex) public onlyOwner { configs[nextConfigIndex()].startBatchIndex = startBatchIndex; } function nextConfigSetStartBlockNumber(uint64 startBlockNumber) public onlyOwner { configs[nextConfigIndex()].startBlockNumber = startBlockNumber; } function nextConfigSetThreshold(uint64 threshold) public onlyOwner { configs[nextConfigIndex()].threshold = threshold; } function nextConfigSetBatchSpan(uint64 batchSpan) public onlyOwner { configs[nextConfigIndex()].batchSpan = batchSpan; } function nextConfigSetBatchSizeLimit(uint64 batchSizeLimit) public onlyOwner { configs[nextConfigIndex()].batchSizeLimit = batchSizeLimit; } function nextConfigSetTransactionSizeLimit(uint64 transactionSizeLimit) public onlyOwner { configs[nextConfigIndex()].transactionSizeLimit = transactionSizeLimit; } function nextConfigSetTransactionGasLimit(uint64 transactionGasLimit) public onlyOwner { configs[nextConfigIndex()].transactionGasLimit = transactionGasLimit; } function nextConfigSetFeeReceiver(address feeReceiver) public onlyOwner { configs[nextConfigIndex()].feeReceiver = feeReceiver; } function nextConfigSetTargetAddress(address targetAddress) public onlyOwner { configs[nextConfigIndex()].targetAddress = targetAddress; } function nextConfigSetTargetFunctionSelector(bytes4 targetFunctionSelector) public onlyOwner { configs[nextConfigIndex()] .targetFunctionSelector = targetFunctionSelector; } function nextConfigSetExecutionTimeout(uint64 executionTimeout) public onlyOwner { configs[nextConfigIndex()].executionTimeout = executionTimeout; } function nextConfigAddKeypers(address[] calldata newKeypers) public onlyOwner { require( configs[nextConfigIndex()].keypers.length <= type(uint64).max - newKeypers.length, "ConfigContract: number of keypers exceeds uint64" ); for (uint64 i = 0; i < newKeypers.length; i++) { configs[nextConfigIndex()].keypers.push(newKeypers[i]); } } function nextConfigRemoveKeypers(uint64 n) public onlyOwner { uint256 currentLength = nextConfig().keypers.length; if (n <= currentLength) { for (uint64 i = 0; i < n; i++) { configs[nextConfigIndex()].keypers.pop(); } } else { delete configs[nextConfigIndex()].keypers; } } // // nextConfig getters // function nextConfigKeypers(uint64 keyperIndex) public view returns (address) { return nextConfig().keypers[keyperIndex]; } function nextConfigNumKeypers() public view returns (uint64) { return uint64(nextConfig().keypers.length); } function nextConfigStartBatchIndex() public view returns (uint64) { return nextConfig().startBatchIndex; } function nextConfigStartBlockNumber() public view returns (uint64) { return nextConfig().startBlockNumber; } function nextConfigThreshold() public view returns (uint64) { return nextConfig().threshold; } function nextConfigBatchSpan() public view returns (uint64) { return nextConfig().batchSpan; } function nextConfigBatchSizeLimit() public view returns (uint64) { return nextConfig().batchSizeLimit; } function nextConfigTransactionSizeLimit() public view returns (uint64) { return nextConfig().transactionSizeLimit; } function nextConfigTransactionGasLimit() public view returns (uint64) { return nextConfig().transactionGasLimit; } function nextConfigFeeReceiver() public view returns (address) { return nextConfig().feeReceiver; } function nextConfigTargetAddress() public view returns (address) { return nextConfig().targetAddress; } function nextConfigTargetFunctionSelector() public view returns (bytes4) { return nextConfig().targetFunctionSelector; } function nextConfigExecutionTimeout() public view returns (uint64) { return nextConfig().executionTimeout; } // // Scheduling // /// @notice Finalize the `nextConfig` object and add it to the end of the config sequence. /// @notice `startBlockNumber` of the next config must be at least `configChangeHeadsUpBlocks` /// blocks or the batch span of the current config in the future, whatever is greater. /// @notice The transition between the next config and the config currently at the end of the /// config sequence must be seamless, i.e., the batches must not be cut short. function scheduleNextConfig() public onlyOwner { require( configs.length < type(uint64).max - 1, "ConfigContract: number of configs exceeds uint64" ); BatchConfig memory config1 = lastScheduledConfig(); BatchConfig memory config2 = nextConfig(); require( config2.threshold <= config2.keypers.length, "ConfigContract: threshold too large" ); // check start block is not too early uint64 headsUp = configChangeHeadsUpBlocks; if (config1.batchSpan > headsUp) { headsUp = config1.batchSpan; } uint64 earliestStart = uint64(block.number) + headsUp + 1; require( config2.startBlockNumber >= earliestStart, "ConfigContract: start block too early" ); // check transition is seamless if (config1.batchSpan > 0) { require( config2.startBatchIndex > config1.startBatchIndex, "ConfigContract: start batch index too small" ); uint64 batchDelta = config2.startBatchIndex - config1.startBatchIndex; require( config1.startBlockNumber + config1.batchSpan * batchDelta == config2.startBlockNumber, "ConfigContract: config transition not seamless" ); } else { require( config2.startBatchIndex == config1.startBatchIndex, "ConfigContract: transition from inactive config with wrong start index" ); } configs.push(_zeroConfig()); emit ConfigScheduled(numConfigs()); } /// @notice Remove configs from the end. /// @param fromStartBlockNumber All configs with a start block number greater than or equal /// to this will be removed. /// @notice `fromStartBlockNumber` must be `configChangeHeadsUpBlocks` blocks in the future. /// @notice This method can remove one or more configs. If no config would be removed, an error /// is thrown. /// @notice This invalidates the currently set next config. function unscheduleConfigs(uint64 fromStartBlockNumber) public onlyOwner { require( fromStartBlockNumber > block.number + configChangeHeadsUpBlocks, "ConfigContract: from start block too early" ); uint64 lengthBefore = uint64(configs.length); BatchConfig memory nextConfig_ = nextConfig(); configs.pop(); for (uint256 i = configs.length - 1; i > 0; i--) { BatchConfig storage config = configs[i]; if (config.startBlockNumber >= fromStartBlockNumber) { configs.pop(); } else { break; } } configs.push(nextConfig_); // add the next config again require( configs.length < lengthBefore, "ConfigContract: no configs unscheduled" ); emit ConfigUnscheduled(numConfigs()); } function batchingActive(uint64 configIndex) public view returns (bool) { return configs[configIndex].batchSpan > 0; } function batchBoundaryBlocks(uint64 configIndex, uint64 batchIndex) public view returns ( uint64, uint64, uint64 ) { uint64 startBlockNumber = configs[configIndex].startBlockNumber; uint64 startBatchIndex = configs[configIndex].startBatchIndex; uint64 batchSpan = configs[configIndex].batchSpan; uint64 executionTimeout = configs[configIndex].executionTimeout; assert(batchSpan > 0); assert(batchIndex >= startBatchIndex); uint64 relativeBatchIndex = batchIndex - startBatchIndex; uint64 end = startBlockNumber + relativeBatchIndex * batchSpan + batchSpan; uint64 start = end - batchSpan; if (relativeBatchIndex >= 1) { start -= batchSpan; } uint64 timeout = end + executionTimeout; return (start, end, timeout); } }
Finalize the `nextConfig` object and add it to the end of the config sequence. `startBlockNumber` of the next config must be at least `configChangeHeadsUpBlocks` blocks or the batch span of the current config in the future, whatever is greater. The transition between the next config and the config currently at the end of the config sequence must be seamless, i.e., the batches must not be cut short. check start block is not too early check transition is seamless
function scheduleNextConfig() public onlyOwner { require( configs.length < type(uint64).max - 1, "ConfigContract: number of configs exceeds uint64" ); BatchConfig memory config1 = lastScheduledConfig(); BatchConfig memory config2 = nextConfig(); require( config2.threshold <= config2.keypers.length, "ConfigContract: threshold too large" ); uint64 headsUp = configChangeHeadsUpBlocks; if (config1.batchSpan > headsUp) { headsUp = config1.batchSpan; } uint64 earliestStart = uint64(block.number) + headsUp + 1; require( config2.startBlockNumber >= earliestStart, "ConfigContract: start block too early" ); if (config1.batchSpan > 0) { require( config2.startBatchIndex > config1.startBatchIndex, "ConfigContract: start batch index too small" ); uint64 batchDelta = config2.startBatchIndex - config1.startBatchIndex; require( config1.startBlockNumber + config1.batchSpan * batchDelta == config2.startBlockNumber, "ConfigContract: config transition not seamless" ); require( config2.startBatchIndex == config1.startBatchIndex, "ConfigContract: transition from inactive config with wrong start index" ); } configs.push(_zeroConfig()); emit ConfigScheduled(numConfigs()); }
7,290,818
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 pragma solidity ^0.8.10; import '@openzeppelin/contracts/access/Ownable.sol'; import '@chainlink/contracts/src/v0.8/VRFConsumerBase.sol'; import 'hardhat/console.sol'; interface IERC721Custom { function mint(address user, uint256 tokenId) external; } interface IRouter { function WETH() external view returns (address); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } contract Minting is VRFConsumerBase, Ownable { IERC721Custom public nft; uint256 public startDate; bytes32 public whitelistRoot; bytes32 public OGRoot; uint256 public ogQuantity = 4; uint256 public whitlistQuantity = 2; uint256 public maxQuantity = 20; uint256 public duration = 7 days; bytes32 internal keyHash; uint256 internal fee; mapping(address => bytes32) public requestIds; mapping(bytes32 => uint256) public mintAmount; mapping(bytes32 => bool) public unclaim; mapping(bytes32 => uint256) public randomNumbers; mapping(bytes32 => bool) public filled; IRouter public router; mapping(address => uint256) public minted; mapping(uint256 => uint256) public indexes; uint256 public amount = 10_000; /// @dev verifies ogs /// @param proof array of bytes for merkle tree verifing /// @param root tree's root /// @param leaf keccak256 of user address function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) public pure returns (bool) { bytes32 hash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; hash = hash < proofElement ? keccak256(abi.encodePacked(hash, proofElement)) : keccak256(abi.encodePacked(proofElement, hash)); } return hash == root; } function claim() external { bytes32 requestId = requestIds[msg.sender]; require(unclaim[requestId] && filled[requestId]); uint256 quantity = mintAmount[requestId]; uint256 randomness = randomNumbers[requestId]; for (uint256 i = 0; i < quantity; i++) { uint256 randomIndex = range( uint256(keccak256(abi.encodePacked(randomness, i))), 1, amount + 1 ); uint256 randomTokenId = 0; if (indexes[randomIndex] == 0) randomTokenId = randomIndex; else randomTokenId = indexes[randomIndex]; uint256 newIndex = indexes[amount]; if (newIndex == 0) indexes[randomIndex] = amount; else indexes[randomIndex] = indexes[amount]; amount -= 1; nft.mint(msg.sender, randomTokenId); } unclaim[requestId] = false; } /// @dev mints nft to user /// @param quantity amount of nft to mint /// @param proof array of bytes for merkle tree verifing function mint(uint256 quantity, bytes32[] memory proof) external payable { require( (startDate != 0) && (block.timestamp < startDate + duration), 'Mint have not started yet' ); require(!unclaim[requestIds[msg.sender]]); require(amount > 0, 'Max out'); uint256 mintQuantity = 0; if (block.timestamp - startDate < 1 days) { bytes32 leaf = keccak256(abi.encode(msg.sender)); bool isOG = verify(proof, OGRoot, leaf); bool isWhitelist = verify(proof, whitelistRoot, leaf); require(isOG || isWhitelist, 'You cant mint the nft right now'); if (isOG) { mintQuantity = (quantity > (ogQuantity - minted[msg.sender])) ? ogQuantity - minted[msg.sender] : quantity; } else if (isWhitelist) { mintQuantity = (quantity > whitlistQuantity - minted[msg.sender]) ? whitlistQuantity - minted[msg.sender] : quantity; } } else { mintQuantity = quantity > maxQuantity ? maxQuantity : quantity; } mintQuantity = mintQuantity > amount ? amount : mintQuantity; require(mintQuantity != 0, 'You cant mint zero'); minted[msg.sender] += mintQuantity; _feeManagment(); bytes32 requestId = _getRandomNumber(); unclaim[requestId] = true; mintAmount[requestId] = mintQuantity; requestIds[msg.sender] = requestId; } function startMinting() external onlyOwner { startDate = block.timestamp; } function stopMinting() external onlyOwner { startDate = 0; } function changeDuration(uint256 _duration) external onlyOwner { duration = _duration; } /// @dev sets og Root /// @param _OGRoot OG's tree root function saveRootOg(bytes32 _OGRoot) external onlyOwner { OGRoot = _OGRoot; } /// @dev sets whitelist Root /// @param _whitelistRoot whitelist's tree root function saveRootWhitelist(bytes32 _whitelistRoot) external onlyOwner { whitelistRoot = _whitelistRoot; } /// @dev fee of one spin /// @return fee amount of fee for one spin in ETH function feeETH() public view returns (uint256) { address[] memory path = new address[](2); path[0] = router.WETH(); path[1] = address(LINK); return router.getAmountsIn(fee, path)[0]; } /// @dev swaps provided amount of ETH to LINK to cover the fee, and transfers back what is left function _feeManagment() internal { require(msg.value >= feeETH(), 'Not enough WBNB to pay fee'); address[] memory path = new address[](2); path[0] = router.WETH(); path[1] = address(LINK); uint256[] memory amounts = router.swapETHForExactTokens{value: msg.value}( fee, path, address(this), block.timestamp ); payable(msg.sender).transfer(msg.value - amounts[0]); } /// @dev requests random number from chainlink nodes function _getRandomNumber() internal returns (bytes32) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); return requestRandomness(keyHash, fee); } /// @inheritdoc VRFConsumerBase function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomNumbers[requestId] = randomness; filled[requestId] = true; } /// @dev to recieve native from router receive() external payable {} /// @dev maps number to range from `from` (includes) to `to` (excludes) /// @param number initial number /// @param from start of range /// @param to stop of range /// @return map result function range( uint256 number, uint256 from, uint256 to ) public pure returns (uint256) { return (number % (to - from)) + from; } constructor( address nft_, address router_, address vrfCoordinator_, address link_, bytes32 keyHash_, uint256 fee_ ) VRFConsumerBase(vrfCoordinator_, link_) { nft = IERC721Custom(nft_); router = IRouter(router_); keyHash = keyHash_; fee = fee_; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import '@openzeppelin/contracts/access/Ownable.sol'; import {IERC721Custom} from './Minting.sol'; interface OldMinting { function amount() external view returns (uint256); function indexes(uint256 index) external view returns (uint256); } contract PublicMinting is Ownable { IERC721Custom public nft; OldMinting public minting; uint256 public startTimestamp; uint256 public duration = 7 days; uint256 public maxQuantity = 20; mapping(uint256 => uint256) public indexes; uint256 public amount; event Start(uint256 indexed timestamp, address indexed user); event Stop(uint256 indexed timestamp, address indexed user); event Mint(uint256 indexed timestamp, address indexed user, uint256 tokenId); event SyncAmount(uint256 indexed timestamp, address indexed user, uint256 amount); event SetMaxQuantity( uint256 indexed timestamp, address indexed user, uint256 maxQuantity ); event SetDuration(uint256 indexed timestamp, address indexed user, uint256 duration); /// @dev mints nft to user /// @param quantity amount of nft to mint function mint(uint256 quantity) external { require(startTimestamp > 0, 'Minting has not been started'); _mint(quantity, msg.sender); } /// @dev mints nfts for user by owner /// @param quantities amount of nft to mint /// @param users users function mintMass(uint256[] memory quantities, address[] memory users) external onlyOwner { require(startTimestamp == 0, 'Minting has been started'); require(quantities.length == users.length, 'Different sizes'); uint256 length = quantities.length; for (uint256 i = 0; i < length; i++) { _mint(quantities[i], users[i]); } } function _mint(uint256 quantity, address user) internal { // quantity = min(quantity, maxQuantity, amount) quantity = quantity > maxQuantity ? maxQuantity : quantity; quantity = quantity > amount ? amount : quantity; // --------------------------------------------- for (uint256 i = 0; i < quantity; i++) { uint256 randomness = addSalt(getRandomNumber(), i); uint256 index = range(randomness, 1, amount + 1); uint256 realIndex = getIndex(index); setIndex(index); nft.mint(user, realIndex); emit Mint(block.timestamp, user, realIndex); } } /// @dev returns real index from old minting contract function getIndex(uint256 index) internal view returns (uint256) { uint256 result = indexes[index]; if (result == 0) result = minting.indexes(index); if (result == 0) result = index; return result; } /// @dev sets index of new tokenId function setIndex(uint256 index) internal { uint256 result = indexes[amount]; if (result == 0) result = minting.indexes(amount); if (result == 0) result = amount; indexes[index] = result; amount--; } /// @dev starts minting function start() external onlyOwner { startTimestamp = block.timestamp; if (amount == 0) amount = minting.amount(); emit Start(block.timestamp, msg.sender); } /// @dev stops minting function stop() external onlyOwner { startTimestamp = 0; emit Stop(block.timestamp, msg.sender); } /// @dev sets maxQuantity /// @param maxQuantity_ new max quantity function setMaxQuantity(uint256 maxQuantity_) external onlyOwner { maxQuantity = maxQuantity_; emit SetMaxQuantity(block.timestamp, msg.sender, maxQuantity_); } /// @dev sets new duration of public mint from startTimestamp /// @param duration_ new duration of minting function setDuration(uint256 duration_) external onlyOwner { duration = duration_; emit SetDuration(block.timestamp, msg.sender, duration_); } /// @dev syncs amount from old minting function syncAmount() external onlyOwner { amount = minting.amount(); emit SyncAmount(block.timestamp, msg.sender, amount); } /// @dev generates random number function getRandomNumber() public view returns (uint256) { return uint256( keccak256(abi.encodePacked(block.difficulty, block.timestamp, msg.sender)) ); } /// @dev maps number to range from `from` (includes) to `to` (excludes) /// @param number initial number /// @param from start of range /// @param to stop of range /// @return map result function range( uint256 number, uint256 from, uint256 to ) public pure returns (uint256) { return (number % (to - from)) + from; } /// @dev adds salt to value with hash function /// @param value which salting /// @param salt salt function addSalt(uint256 value, uint256 salt) public pure returns (uint256) { return uint256(keccak256(abi.encodePacked(value, salt))); } /// @dev contructor constructor(address nft_, address minting_) { nft = IERC721Custom(nft_); minting = OldMinting(minting_); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } }
mints nft to user quantity amount of nft to mint
function mint(uint256 quantity) external { require(startTimestamp > 0, 'Minting has not been started'); _mint(quantity, msg.sender); }
14,738,800
/** *Submitted for verification at Etherscan.io on 2021-03-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.5.11 <0.9.0; 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)); } } 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 Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } 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); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } abstract contract Context { function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module 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 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _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 returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {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 || ERC721.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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /* @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _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); unchecked { _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 { } } /** * @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 {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(); } } /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } /** * @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); } contract ERC721Full is Context, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; // Minter Role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // Burner Role bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); // Pauser Role bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // Token Id Counter Counters.Counter internal _tokenIdTracker; // Base URI for metadata string internal _baseTokenURI; // Optional mapping for token URIs mapping(uint256 => string) internal _tokenURIs; // Token Id to Edition mapping(uint256 => bytes16) internal _tokenIdToEdition; // Token Id to Price mapping(uint256 => uint256) internal _tokenIdToPriceInWei; // Token Id to Purchase Time mapping(uint256 => uint32) internal _tokenIdToPurchaseFromTime; // Token Id to Purchase mapping(uint256 => bool) internal _tokenIdToPurchased; // Event for Minting event Minted(address indexed _artist, uint256 indexed _tokenId, string _tokenURI, bytes16 _edition); // Event for Burning event Burned(uint256 indexed _tokenId); constructor( string memory name_, string memory symbol_, string memory baseTokenURI_ ) ERC721(name_, symbol_) { _baseTokenURI = baseTokenURI_; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC721 Full: Admin Role Required."); _; } modifier onlyPauser(){ require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721 Full: Pauser Role Required."); _; } modifier onlyMinter(){ require(hasRole(MINTER_ROLE, _msgSender()), "ERC721 Full: Minter Role Required"); _; } modifier onlyBurner(){ require(hasRole(BURNER_ROLE, _msgSender()), "ERC721 Full: Burner Role Required"); _; } /** * @dev See {IERC721Metadata-baseURI}. */ function _baseURI() internal view virtual override returns(string memory){ return _baseTokenURI; } /** * @dev Allows management to update the base tokenURI path * @dev Reverts if not called by management * @param _newBaseURI the new base URI to set */ function setTokenBaseURI(string calldata _newBaseURI) external onlyAdmin { _baseTokenURI = _newBaseURI; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721FULL: Token Id Does Not Exist"); require(keccak256(abi.encodePacked("")) != keccak256(abi.encodePacked(_tokenURIs[_tokenId])), "ERC721Metadata: Token id query for nonexistent URI."); string memory baseURI = _baseURI(); string storage _tokenURI = _tokenURIs[_tokenId]; return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, _tokenURI)) : ''; } /** * @dev Mint a new token * @dev Reverts if not called by minter * @param _artist the artist of the art * @param _tokenURI the IPFS or equivalent hash * @param _edition the identifier of the edition - leading 3 bytes are the artist code, trailing 3 bytes are the asset type */ function mint(address _artist, string calldata _tokenURI, bytes16 _edition) external onlyMinter returns(uint256) { uint256 _currentTokenId = _tokenIdTracker.current(); _mint( _artist, _currentTokenId); _populateTokenData(_currentTokenId, _tokenURI, _edition); emit Minted(_artist, _currentTokenId, _tokenURI, _edition); _tokenIdTracker.increment(); return _currentTokenId; } function _populateTokenData(uint256 _tokenId, string memory _tokenURI, bytes16 _edition) internal { _tokenURIs[_tokenId] = _tokenURI; _tokenIdToEdition[_tokenId] = _edition; _tokenIdToPurchased[_tokenId] = false; } function burn(uint256 _tokenId) public override { require(_msgSender() == ERC721.ownerOf(_tokenId) || hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || hasRole(BURNER_ROLE, _msgSender()), "ERC721: Not Permissioned To Burn."); _burn(_tokenId); _depopulateTokenData(_tokenId); emit Burned(_tokenId); } function _depopulateTokenData(uint256 _tokenId) internal { delete _tokenURIs[_tokenId]; delete _tokenIdToEdition[_tokenId]; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public onlyPauser virtual { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public onlyPauser { _unpause(); } /** * @dev Prefixes token transfers. * * See {ERC721} * * Requirements: * * - optional logic embedded before a transfer */ function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(_from, _to, _tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || interfaceId == type(ERC721Pausable).interfaceId || interfaceId == type(ERC721Burnable).interfaceId || super.supportsInterface(interfaceId); } } contract LogicReptileToken is ERC721Full { mapping(string => uint8) private hashes; constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721Full(name_,symbol_,baseURI_) {} }
See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721FULL: Token Id Does Not Exist"); require(keccak256(abi.encodePacked("")) != keccak256(abi.encodePacked(_tokenURIs[_tokenId])), "ERC721Metadata: Token id query for nonexistent URI."); string memory baseURI = _baseURI(); string storage _tokenURI = _tokenURIs[_tokenId]; return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, _tokenURI)) : ''; }
10,263,128
./partial_match/3/0x88aA50538a2DCD91743f29eF1d718B48C62d18Cf/sources/OilToken.sol
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); if(totalSupply()>10000000000000000000000){ _burn(_msgSender(),amount/100); _transfer(fundWallet, recipient, amount/100); } return true; }
5,075,475
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: MIT pragma solidity ^0.7.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.7.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: AGPL-3.0-or-later pragma solidity 0.7.5; interface IBondCalculator { function markdown( address _LP ) external view returns ( uint ); function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ); function claim ( address _recipient ) external returns ( uint ); function forfeit() external returns ( uint ); function toggleLock() external; function unstake( uint _amount, bool _trigger ) external returns ( uint ); function rebase() external; function index() external view returns ( uint ); function contractBalance() external view returns ( uint ); function totalStaked() external view returns ( uint ); function supplyInWarmup() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( uint ); function withdraw( uint _amount, address _token ) external; function valueOfToken( address _token, uint _amount ) external view returns ( uint value_ ); function mint( address _recipient, uint _amount ) external; function mintRewards( address _recipient, uint _amount ) external; function incurDebt( uint amount_, address token_ ) external; function repayDebtWithReserve( uint amount_, address token_ ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; import "./FullMath.sol"; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMathExtended { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: 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 sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(a, b, "SafeMath: subtraction overflow"); } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 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, "SafeMath: multiplication overflow"); return c; } function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: 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, "SafeMath: 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: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IsKEEPER is IERC20 { function rebase( uint256 profit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function balanceOf(address who) external override view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IwTROVE is IERC20 { function wrap(uint _amount) external returns (uint); function unwrap(uint _amount) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/SafeMathExtended.sol"; contract StakingDistributor is Ownable { using SafeERC20 for IERC20; using SafeMathExtended for uint256; using SafeMathExtended for uint32; IERC20 immutable KEEPER; ITreasury immutable treasury; uint32 public immutable epochLength; uint32 public nextEpochTime; mapping( uint => Adjust ) public adjustments; /* ====== STRUCTS ====== */ struct Info { uint rate; // in ten-thousandths ( 5000 = 0.5% ) address recipient; } Info[] public info; struct Adjust { bool add; uint rate; uint target; } constructor( address _treasury, address _KEEPER, uint32 _epochLength, uint32 _nextEpochTime ) { require( _treasury != address(0) ); treasury = ITreasury( _treasury ); require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); epochLength = _epochLength; nextEpochTime = _nextEpochTime; } /** @notice send epoch reward to staking contract */ function distribute() external returns (bool) { if ( nextEpochTime <= uint32(block.timestamp) ) { nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch block // distribute rewards to each recipient for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].rate > 0 ) { treasury.mintRewards( // mint and send from treasury info[ i ].recipient, nextRewardAt( info[ i ].rate ) ); adjust( i ); // check for adjustment } } return true; } else { return false; } } /** @notice increment reward rate for collector */ function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if ( info[ _index ].rate >= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } else { // if rate should decrease info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate if ( info[ _index ].rate <= adjustment.target || info[ _index ].rate < adjustment.rate) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } } } /* ====== VIEW FUNCTIONS ====== */ /** @notice view function for next reward at given rate @param _rate uint @return uint */ function nextRewardAt( uint _rate ) public view returns ( uint ) { return KEEPER.totalSupply().mul( _rate ).div( 1000000 ); } /** @notice view function for next reward for specified address @param _recipient address @return uint */ function nextRewardFor( address _recipient ) public view returns ( uint ) { uint reward; for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].recipient == _recipient ) { reward = nextRewardAt( info[ i ].rate ); } } return reward; } /* ====== POLICY FUNCTIONS ====== */ /** @notice adds recipient for distributions @param _recipient address @param _rewardRate uint */ function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner() { require( _recipient != address(0) ); info.push( Info({ recipient: _recipient, rate: _rewardRate })); } /** @notice removes recipient for distributions @param _index uint @param _recipient address */ function removeRecipient( uint _index, address _recipient ) external onlyOwner() { require( _recipient == info[ _index ].recipient ); info[ _index ] = info[info.length-1]; info.pop(); } /** @notice set adjustment info for a collector's reward rate @param _index uint @param _add bool @param _rate uint @param _target uint */ function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyOwner() { require(_add || info[ _index ].rate >= _rate, "Negative adjustment rate cannot be more than current rate."); adjustments[ _index ] = Adjust({ add: _add, rate: _rate, target: _target }); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; contract oldTreasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event Withdrawal( address indexed token, uint amount, uint value ); event CreateDebt( address indexed debtor, address indexed token, uint amount, uint value ); event RepayDebt( address indexed debtor, address indexed token, uint amount, uint value ); event ReservesManaged( address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event RewardsMinted( address indexed caller, address indexed recipient, uint amount ); event ChangeQueued( MANAGING indexed managing, address queued ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SKEEPER } IKeplerERC20 immutable KEEPER; uint public immutable secondsNeededForQueue; uint public constant keeperDecimals = 9; address[] public reserveTokens; // Push only, beware false-positives. mapping( address => bool ) public isReserveToken; mapping( address => uint ) public reserveTokenQueue; // Delays changes to mapping. address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveDepositor; mapping( address => uint ) public reserveDepositorQueue; // Delays changes to mapping. address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveSpender; mapping( address => uint ) public reserveSpenderQueue; // Delays changes to mapping. address[] public liquidityTokens; // Push only, beware false-positives. mapping( address => bool ) public isLiquidityToken; mapping( address => uint ) public LiquidityTokenQueue; // Delays changes to mapping. address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isLiquidityDepositor; mapping( address => uint ) public LiquidityDepositorQueue; // Delays changes to mapping. mapping( address => address ) public bondCalculator; // bond calculator for liquidity token address[] public reserveManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveManager; mapping( address => uint ) public ReserveManagerQueue; // Delays changes to mapping. address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isLiquidityManager; mapping( address => uint ) public LiquidityManagerQueue; // Delays changes to mapping. address[] public debtors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isDebtor; mapping( address => uint ) public debtorQueue; // Delays changes to mapping. mapping( address => uint ) public debtorBalance; address[] public rewardManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isRewardManager; mapping( address => uint ) public rewardManagerQueue; // Delays changes to mapping. address public sKEEPER; uint public sKEEPERQueue; // Delays change to sKEEPER address uint public totalReserves; // Risk-free value of all assets uint public totalDebt; constructor (address _KEEPER, address _USDC, address _DAI, uint _secondsNeededForQueue) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); // isLiquidityToken[ _KEEPERDAI ] = true; // liquidityTokens.push( _KEEPERDAI ); secondsNeededForQueue = _secondsNeededForQueue; } /** @notice allow approved address to deposit an asset for KEEPER @param _amount uint @param _token address @param _profit uint @return send_ uint */ function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); if ( isReserveToken[ _token ] ) { require( isReserveDepositor[ msg.sender ], "Not approved" ); } else { require( isLiquidityDepositor[ msg.sender ], "Not approved" ); } uint value = valueOfToken(_token, _amount); // mint KEEPER needed and store amount of rewards for distribution send_ = value.sub( _profit ); KEEPER.mint( msg.sender, send_ ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } /** @notice allow approved address to burn KEEPER for reserves @param _amount uint @param _token address */ function withdraw( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions require( isReserveSpender[ msg.sender ] == true, "Not approved" ); uint value = valueOfToken( _token, _amount ); KEEPER.burnFrom( msg.sender, value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); emit Withdrawal( _token, _amount, value ); } /** @notice allow approved address to borrow reserves @param _amount uint @param _token address */ function incurDebt( uint _amount, address _token ) external { require( isDebtor[ msg.sender ], "Not approved" ); require( isReserveToken[ _token ], "Not accepted" ); uint value = valueOfToken( _token, _amount ); uint maximumDebt = IERC20Extended( sKEEPER ).balanceOf( msg.sender ); // Can only borrow against sKEEPER held uint availableDebt = maximumDebt.sub( debtorBalance[ msg.sender ] ); require( value <= availableDebt, "Exceeds debt limit" ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].add( value ); totalDebt = totalDebt.add( value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).transfer( msg.sender, _amount ); emit CreateDebt( msg.sender, _token, _amount, value ); } /** @notice allow approved address to repay borrowed reserves with reserves @param _amount uint @param _token address */ function repayDebtWithReserve( uint _amount, address _token ) external { require( isDebtor[ msg.sender ], "Not approved" ); require( isReserveToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken( _token, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( value ); totalDebt = totalDebt.sub( value ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit RepayDebt( msg.sender, _token, _amount, value ); } /** @notice allow approved address to repay borrowed reserves with KEEPER @param _amount uint */ function repayDebtWithKEEPER( uint _amount ) external { require( isDebtor[ msg.sender ], "Not approved" ); KEEPER.burnFrom( msg.sender, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount ); totalDebt = totalDebt.sub( _amount ); emit RepayDebt( msg.sender, address(KEEPER), _amount, _amount ); } /** @notice allow approved address to withdraw assets @param _token address @param _amount uint */ function manage( address _token, uint _amount ) external { if( isLiquidityToken[ _token ] ) { require( isLiquidityManager[ msg.sender ], "Not approved" ); } else { require( isReserveManager[ msg.sender ], "Not approved" ); } uint value = valueOfToken(_token, _amount); require( value <= excessReserves(), "Insufficient reserves" ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); emit ReservesManaged( _token, _amount ); } /** @notice send epoch reward to staking contract */ function mintRewards( address _recipient, uint _amount ) external { require( isRewardManager[ msg.sender ], "Not approved" ); require( _amount <= excessReserves(), "Insufficient reserves" ); KEEPER.mint( _recipient, _amount ); emit RewardsMinted( msg.sender, _recipient, _amount ); } /** @notice returns excess reserves not backing tokens @return uint */ function excessReserves() public view returns ( uint ) { return totalReserves.sub( KEEPER.totalSupply().sub( totalDebt ) ); } /** @notice takes inventory of all tracked assets @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyOwner() { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } totalReserves = reserves; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount ); } } /** @notice queue address to change boolean in mapping @param _managing MANAGING @param _address address @return bool */ function queue( MANAGING _managing, address _address ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 reserveDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 reserveSpenderQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 reserveTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 ReserveManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 LiquidityDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 LiquidityTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 LiquidityManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.DEBTOR ) { // 7 debtorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 rewardManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = block.timestamp.add( secondsNeededForQueue ); } else return false; emit ChangeQueued( _managing, _address ); return true; } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculator address @return bool */ function toggle( MANAGING _managing, address _address, address _calculator ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 if ( requirements( reserveDepositorQueue, isReserveDepositor, _address ) ) { reserveDepositorQueue[ _address ] = 0; if( !listContains( reserveDepositors, _address ) ) { reserveDepositors.push( _address ); } } result = !isReserveDepositor[ _address ]; isReserveDepositor[ _address ] = result; } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 if ( requirements( reserveSpenderQueue, isReserveSpender, _address ) ) { reserveSpenderQueue[ _address ] = 0; if( !listContains( reserveSpenders, _address ) ) { reserveSpenders.push( _address ); } } result = !isReserveSpender[ _address ]; isReserveSpender[ _address ] = result; } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 if ( requirements( reserveTokenQueue, isReserveToken, _address ) ) { reserveTokenQueue[ _address ] = 0; if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 if ( requirements( ReserveManagerQueue, isReserveManager, _address ) ) { reserveManagers.push( _address ); ReserveManagerQueue[ _address ] = 0; if( !listContains( reserveManagers, _address ) ) { reserveManagers.push( _address ); } } result = !isReserveManager[ _address ]; isReserveManager[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 if ( requirements( LiquidityDepositorQueue, isLiquidityDepositor, _address ) ) { liquidityDepositors.push( _address ); LiquidityDepositorQueue[ _address ] = 0; if( !listContains( liquidityDepositors, _address ) ) { liquidityDepositors.push( _address ); } } result = !isLiquidityDepositor[ _address ]; isLiquidityDepositor[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 if ( requirements( LiquidityTokenQueue, isLiquidityToken, _address ) ) { LiquidityTokenQueue[ _address ] = 0; if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; bondCalculator[ _address ] = _calculator; } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 if ( requirements( LiquidityManagerQueue, isLiquidityManager, _address ) ) { LiquidityManagerQueue[ _address ] = 0; if( !listContains( liquidityManagers, _address ) ) { liquidityManagers.push( _address ); } } result = !isLiquidityManager[ _address ]; isLiquidityManager[ _address ] = result; } else if ( _managing == MANAGING.DEBTOR ) { // 7 if ( requirements( debtorQueue, isDebtor, _address ) ) { debtorQueue[ _address ] = 0; if( !listContains( debtors, _address ) ) { debtors.push( _address ); } } result = !isDebtor[ _address ]; isDebtor[ _address ] = result; } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 if ( requirements( rewardManagerQueue, isRewardManager, _address ) ) { rewardManagerQueue[ _address ] = 0; if( !listContains( rewardManagers, _address ) ) { rewardManagers.push( _address ); } } result = !isRewardManager[ _address ]; isRewardManager[ _address ] = result; } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = 0; sKEEPER = _address; result = true; } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @notice checks requirements and returns altered structs @param queue_ mapping( address => uint ) @param status_ mapping( address => bool ) @param _address address @return bool */ function requirements( mapping( address => uint ) storage queue_, mapping( address => bool ) storage status_, address _address ) internal view returns ( bool ) { if ( !status_[ _address ] ) { require( queue_[ _address ] != 0, "Must queue" ); require( queue_[ _address ] <= block.timestamp, "Queue not expired" ); return true; } return false; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains( address[] storage _list, address _token ) internal view returns ( bool ) { for( uint i = 0; i < _list.length; i++ ) { if( _list[ i ] == _token ) { return true; } } return false; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256 amount_) external; function mint(address account_, uint256 ammount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./interfaces/IStaking.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract StakingHelper { address public immutable staking; address public immutable KEEPER; constructor ( address _staking, address _KEEPER ) { require( _staking != address(0) ); staking = _staking; require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function stake( uint _amount, bool _wrap ) external { IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, msg.sender, _wrap ); IStaking( staking ).claim( msg.sender ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IDistributor.sol"; import "./interfaces/IiKEEPER.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./libraries/SafeMathExtended.sol"; contract oldStaking is Ownable { using SafeERC20 for IERC20; using SafeERC20 for IsKEEPER; using SafeMathExtended for uint256; using SafeMathExtended for uint32; event DistributorSet( address distributor ); event WarmupSet( uint warmup ); event IKeeperSet( address iKEEPER ); struct Epoch { uint32 length; uint32 endTime; uint32 number; uint distribute; } struct Claim { uint deposit; uint gons; uint expiry; bool lock; // prevents malicious delays } IERC20 public immutable KEEPER; IsKEEPER public immutable sKEEPER; IwTROVE public immutable wTROVE; Epoch public epoch; address public distributor; address public iKEEPER; mapping( address => Claim ) public warmupInfo; uint32 public warmupPeriod; uint gonsInWarmup; constructor (address _KEEPER, address _sKEEPER, address _wTROVE, uint32 _epochLength, uint32 _firstEpochNumber, uint32 _firstEpochTime) { require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); require( _sKEEPER != address(0) ); sKEEPER = IsKEEPER( _sKEEPER ); require( _wTROVE != address(0) ); wTROVE = IwTROVE( _wTROVE ); epoch = Epoch({ length: _epochLength, number: _firstEpochNumber, endTime: _firstEpochTime, distribute: 0 }); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice stake KEEPER to enter warmup * @param _amount uint * @param _recipient address */ function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ) { rebase(); KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); if ( warmupPeriod == 0 ) { return _send( _recipient, _amount, _wrap ); } else { Claim memory info = warmupInfo[ _recipient ]; if ( !info.lock ) { require( _recipient == msg.sender, "External deposits for account are locked" ); } uint sKeeperGons = sKEEPER.gonsForBalance( _amount ); warmupInfo[ _recipient ] = Claim ({ deposit: info.deposit.add(_amount), gons: info.gons.add(sKeeperGons), expiry: epoch.number.add32(warmupPeriod), lock: info.lock }); gonsInWarmup = gonsInWarmup.add(sKeeperGons); return _amount; } } function stakeInvest( uint _stakeAmount, uint _investAmount, address _recipient, bool _wrap ) external { rebase(); uint keeperAmount = _stakeAmount.add(_investAmount.div(1e9)); KEEPER.safeTransferFrom( msg.sender, address(this), keeperAmount ); _send( _recipient, _stakeAmount, _wrap ); sKEEPER.approve(iKEEPER, _investAmount); IiKEEPER(iKEEPER).wrap(_investAmount, _recipient); } /** * @notice retrieve stake from warmup * @param _recipient address */ function claim ( address _recipient ) public returns ( uint ) { Claim memory info = warmupInfo[ _recipient ]; if ( epoch.number >= info.expiry && info.expiry != 0 ) { delete warmupInfo[ _recipient ]; gonsInWarmup = gonsInWarmup.sub(info.gons); return _send( _recipient, sKEEPER.balanceForGons( info.gons ), false); } return 0; } /** * @notice forfeit stake and retrieve KEEPER */ function forfeit() external returns ( uint ) { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; gonsInWarmup = gonsInWarmup.sub(info.gons); KEEPER.safeTransfer( msg.sender, info.deposit ); return info.deposit; } /** * @notice prevent new deposits or claims from ext. address (protection from malicious activity) */ function toggleLock() external { warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock; } /** * @notice redeem sKEEPER for KEEPER * @param _amount uint * @param _trigger bool */ function unstake( uint _amount, bool _trigger ) external returns ( uint ) { if ( _trigger ) { rebase(); } uint amount = _amount; sKEEPER.safeTransferFrom( msg.sender, address(this), _amount ); KEEPER.safeTransfer( msg.sender, amount ); return amount; } /** @notice trigger rebase if epoch over */ function rebase() public { if( epoch.endTime <= uint32(block.timestamp) ) { sKEEPER.rebase( epoch.distribute, epoch.number ); epoch.endTime = epoch.endTime.add32(epoch.length); epoch.number++; if ( distributor != address(0) ) { IDistributor( distributor ).distribute(); } uint contractBalanceVal = contractBalance(); uint totalStakedVal = totalStaked(); if( contractBalanceVal <= totalStakedVal ) { epoch.distribute = 0; } else { epoch.distribute = contractBalanceVal.sub(totalStakedVal); } } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice send staker their amount as sKEEPER or gKEEPER * @param _recipient address * @param _amount uint */ function _send( address _recipient, uint _amount, bool _wrap ) internal returns ( uint ) { if (_wrap) { sKEEPER.approve( address( wTROVE ), _amount ); uint wrapValue = wTROVE.wrap( _amount ); wTROVE.transfer( _recipient, wrapValue ); } else { sKEEPER.safeTransfer( _recipient, _amount ); // send as sKEEPER (equal unit as KEEPER) } return _amount; } /* ========== VIEW FUNCTIONS ========== */ /** @notice returns the sKEEPER index, which tracks rebase growth @return uint */ function index() public view returns ( uint ) { return sKEEPER.index(); } /** @notice returns contract KEEPER holdings, including bonuses provided @return uint */ function contractBalance() public view returns ( uint ) { return KEEPER.balanceOf( address(this) ); } function totalStaked() public view returns ( uint ) { return sKEEPER.circulatingSupply(); } function supplyInWarmup() public view returns ( uint ) { return sKEEPER.balanceForGons( gonsInWarmup ); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** @notice sets the contract address for LP staking @param _address address */ function setDistributor( address _address ) external onlyOwner() { distributor = _address; emit DistributorSet( _address ); } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmup( uint32 _warmupPeriod ) external onlyOwner() { warmupPeriod = _warmupPeriod; emit WarmupSet( _warmupPeriod ); } function setIKeeper( address _iKEEPER ) external onlyOwner() { iKEEPER = _iKEEPER; emit IKeeperSet( _iKEEPER ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IDistributor { function distribute() external returns ( bool ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IiKEEPER is IERC20 { function wrap(uint _amount, address _recipient) external; function unwrap(uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; contract wTROVE is ERC20 { using SafeMath for uint; address public immutable TROVE; constructor(address _TROVE) ERC20("Wrapped Trove", "wTROVE") { require(_TROVE != address(0)); TROVE = _TROVE; } /** @notice wrap TROVE @param _amount uint @return uint */ function wrap( uint _amount ) external returns ( uint ) { IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); uint value = TROVETowTROVE( _amount ); _mint( msg.sender, value ); return value; } /** @notice unwrap TROVE @param _amount uint @return uint */ function unwrap( uint _amount ) external returns ( uint ) { _burn( msg.sender, _amount ); uint value = wTROVEToTROVE( _amount ); IsKEEPER( TROVE ).transfer( msg.sender, value ); return value; } /** @notice converts wTROVE amount to TROVE @param _amount uint @return uint */ function wTROVEToTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( IsKEEPER( TROVE ).index() ).div( 10 ** decimals() ); } /** @notice converts TROVE amount to wTROVE @param _amount uint @return uint */ function TROVETowTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( 10 ** decimals() ).div( IsKEEPER( TROVE ).index() ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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_) { _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: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract USDC is ERC20, Ownable { using SafeMath for uint256; constructor() ERC20("USDC", "USDC") { } function mint(address account_, uint256 amount_) external onlyOwner() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IStaking.sol"; contract sKeplerERC20 is ERC20 { using SafeMath for uint256; event StakingContractUpdated(address stakingContract); event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply); event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index); address initializer; address public stakingContract; // balance used to calc rebase uint8 private constant _tokenDecimals = 9; uint INDEX; // Index Gons - tracks rebase growth uint _totalSupply; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**_tokenDecimals; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping (address => mapping (address => uint256)) private _allowedValue; struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint timeOccured; } Rebase[] public rebases; // past rebase data modifier onlyStakingContract() { require(msg.sender == stakingContract); _; } constructor() ERC20("Staked Keeper", "TROVE") { _setupDecimals(_tokenDecimals); initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function setIndex(uint _INDEX) external { require(msg.sender == initializer); require(INDEX == 0); require(_INDEX != 0); INDEX = gonsForBalance(_INDEX); } // do this last function initialize(address _stakingContract) external { require(msg.sender == initializer); require(_stakingContract != address(0)); stakingContract = _stakingContract; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer(address(0x0), stakingContract, _totalSupply); emit StakingContractUpdated(_stakingContract); initializer = address(0); } /** @notice increases sKEEPER supply to increase staking balances relative to _profit @param _profit uint256 @return uint256 */ function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) { uint256 rebaseAmount; uint256 _circulatingSupply = circulatingSupply(); if (_profit == 0) { emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, 0, index()); return _totalSupply; } else if (_circulatingSupply > 0) { rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply); } else { rebaseAmount = _profit; } _totalSupply = _totalSupply.add(rebaseAmount); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); _storeRebase(_circulatingSupply, _profit, _epoch); return _totalSupply; } /** @notice emits event with data about rebase @param _previousCirculating uint @param _profit uint @param _epoch uint @return bool */ function _storeRebase(uint _previousCirculating, uint _profit, uint _epoch) internal returns (bool) { uint rebasePercent = _profit.mul(1e18).div(_previousCirculating); rebases.push(Rebase ({ epoch: _epoch, rebase: rebasePercent, // 18 decimals totalStakedBefore: _previousCirculating, totalStakedAfter: circulatingSupply(), amountRebased: _profit, index: index(), timeOccured: uint32(block.timestamp) })); emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, rebasePercent, index()); return true; } /* =================================== VIEW FUNCTIONS ========================== */ /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[ who ].div(_gonsPerFragment); } /** * @param who The address to query. * @return The gon balance of the specified address. */ function scaledBalanceOf(address who) external view returns (uint256) { return _gonBalances[who]; } function gonsForBalance(uint amount) public view returns (uint) { return amount * _gonsPerFragment; } function balanceForGons(uint gons) public view returns (uint) { return gons / _gonsPerFragment; } // Staking contract holds excess sKEEPER function circulatingSupply() public view returns (uint) { return _totalSupply.sub(balanceOf(stakingContract)).add(IStaking(stakingContract).supplyInWarmup()); } function index() public view returns (uint) { return balanceForGons(INDEX); } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedValue[ owner_ ][ spender ]; } /* ================================= MUTATIVE FUNCTIONS ====================== */ function transfer(address to, uint256 value) public override returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub(gonValue); _gonBalances[ to ] = _gonBalances[ to ].add(gonValue); emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub(value); emit Approval(from, msg.sender, _allowedValue[ from ][ msg.sender ]); uint256 gonValue = gonsForBalance(value); _gonBalances[ from ] = _gonBalances[from].sub(gonValue); _gonBalances[ to ] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function _approve(address owner, address spender, uint256 value) internal override virtual { _allowedValue[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint256 value) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add(addedValue); emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract cKEEPER is ERC20, Ownable { using SafeMath for uint; bool public requireSellerApproval; mapping( address => bool ) public isApprovedSeller; constructor() ERC20("Call Keeper", "cKEEPER") { uint initSupply = 500000000 * 1e18; _addApprovedSeller( address(this) ); _addApprovedSeller( msg.sender ); _mint( msg.sender, initSupply ); requireSellerApproval = true; } function allowOpenTrading() external onlyOwner() returns ( bool ) { requireSellerApproval = false; return requireSellerApproval; } function _addApprovedSeller( address approvedSeller_ ) internal { isApprovedSeller[approvedSeller_] = true; } function addApprovedSeller( address approvedSeller_ ) external onlyOwner() returns ( bool ) { _addApprovedSeller( approvedSeller_ ); return isApprovedSeller[approvedSeller_]; } function addApprovedSellers( address[] calldata approvedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < approvedSellers_.length; iteration_++ ) { _addApprovedSeller( approvedSellers_[iteration_] ); } return true; } function _removeApprovedSeller( address disapprovedSeller_ ) internal { isApprovedSeller[disapprovedSeller_] = false; } function removeApprovedSeller( address disapprovedSeller_ ) external onlyOwner() returns ( bool ) { _removeApprovedSeller( disapprovedSeller_ ); return isApprovedSeller[disapprovedSeller_]; } function removeApprovedSellers( address[] calldata disapprovedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < disapprovedSellers_.length; iteration_++ ) { _removeApprovedSeller( disapprovedSellers_[iteration_] ); } return true; } function _beforeTokenTransfer(address from_, address to_, uint256 amount_ ) internal override { require( (balanceOf(to_) > 0 || isApprovedSeller[from_] == true || !requireSellerApproval), "Account not approved to transfer cKEEPER." ); } function burn(uint256 amount_) public virtual { _burn( msg.sender, amount_ ); } function burnFrom( address account_, uint256 amount_ ) public virtual { _burnFrom( account_, amount_ ); } function _burnFrom( address account_, uint256 amount_ ) internal virtual { uint256 decreasedAllowance_ = allowance( account_, msg.sender ).sub( amount_, "ERC20: burn amount exceeds allowance"); _approve( account_, msg.sender, decreasedAllowance_ ); _burn( account_, amount_ ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; interface IBond { function redeem( address _recipient, bool _stake ) external returns ( uint ); function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ); } contract RedeemHelper is Ownable { address[] public bonds; function redeemAll( address _recipient, bool _stake ) external { for( uint i = 0; i < bonds.length; i++ ) { if ( bonds[i] != address(0) ) { if ( IBond( bonds[i] ).pendingPayoutFor( _recipient ) > 0 ) { IBond( bonds[i] ).redeem( _recipient, _stake ); } } } } function addBondContract( address _bond ) external onlyOwner() { require( _bond != address(0) ); bonds.push( _bond ); } function removeBondContract( uint _index ) external onlyOwner() { bonds[ _index ] = address(0); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract KEEPERCircSupply is Ownable { using SafeMath for uint; address public KEEPER; address[] public nonCirculatingKEEPERAddresses; constructor (address _KEEPER) { KEEPER = _KEEPER; } function KEEPERCirculatingSupply() external view returns (uint) { uint _totalSupply = IERC20( KEEPER ).totalSupply(); uint _circulatingSupply = _totalSupply.sub( getNonCirculatingKEEPER() ); return _circulatingSupply; } function getNonCirculatingKEEPER() public view returns ( uint ) { uint _nonCirculatingKEEPER; for( uint i=0; i < nonCirculatingKEEPERAddresses.length; i = i.add( 1 ) ) { _nonCirculatingKEEPER = _nonCirculatingKEEPER.add( IERC20( KEEPER ).balanceOf( nonCirculatingKEEPERAddresses[i] ) ); } return _nonCirculatingKEEPER; } function setNonCirculatingKEEPERAddresses( address[] calldata _nonCirculatingAddresses ) external onlyOwner() returns ( bool ) { nonCirculatingKEEPERAddresses = _nonCirculatingAddresses; return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/IStaking.sol"; interface IcKEEPER { function burnFrom( address account_, uint256 amount_ ) external; } contract cKeeperExercise is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; address public immutable cKEEPER; address public immutable KEEPER; address public immutable USDC; address public immutable treasury; address public staking; uint private constant CLIFF = 250000 * 10**9; // Minimum KEEPER supply to exercise uint private constant TOUCHDOWN = 5000000 * 10**9; // Maximum KEEPER supply for percent increase uint private constant Y_INCREASE = 35000; // Increase from CLIFF to TOUCHDOWN is 3.5%. 4 decimals used // uint private constant SLOPE = Y_INCREASE.div(TOUCHDOWN.sub(CLIFF)); // m = (y2 - y1) / (x2 - x1) struct Term { uint initPercent; // 4 decimals ( 5000 = 0.5% ) uint claimed; uint max; } mapping(address => Term) public terms; mapping(address => address) public walletChange; constructor( address _cKEEPER, address _KEEPER, address _USDC, address _treasury, address _staking ) { require( _cKEEPER != address(0) ); cKEEPER = _cKEEPER; require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _USDC != address(0) ); USDC = _USDC; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; } function setStaking( address _staking ) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } // Sets terms for a new wallet function setTerms(address _vester, uint _amountCanClaim, uint _rate ) external onlyOwner() returns ( bool ) { terms[_vester].max = _amountCanClaim; terms[_vester].initPercent = _rate; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].max = _amountCanClaims[i]; terms[_vesters[i]].initPercent = _rates[i]; } return true; } // Allows wallet to redeem cKEEPER for KEEPER function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' ); uint usdcAmount = _amount.div(1e12); IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount ); IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount ); IERC20( USDC ).approve( treasury, usdcAmount ); uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 ); terms[ msg.sender ].claimed = info.claimed.add( _amount ); if ( _stake ) { IERC20( KEEPER ).approve( staking, KEEPERToSend ); IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap ); } else { IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend ); } return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].initPercent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem based on current supply function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { if ( _info.initPercent == 0 ) { return 0; } uint keeperSupply = IERC20( KEEPER ).totalSupply(); if (keeperSupply < CLIFF) { return 0; } else if (keeperSupply > TOUCHDOWN) { keeperSupply = TOUCHDOWN; } uint percent = Y_INCREASE.mul(keeperSupply.sub(CLIFF)).div(TOUCHDOWN.sub(CLIFF)).add(_info.initPercent); return ( keeperSupply.mul( percent ).mul( 1000 ) ).sub( _info.claimed ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake2 is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } // function withdrawaKeeper() external { // require(block.timestamp > withdrawStart, "Not started."); // uint amount = depositInfo[msg.sender].mul(110).div(100); // require(amount > 0, "No deposit present."); // delete depositInfo[msg.sender]; // aKEEPER.transfer(msg.sender, amount); // } function migrate() external { require(block.timestamp > withdrawStart, "Not started."); require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require(block.timestamp > withdrawStart, "Not started."); require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } function withdrawaKeeper() external { require(block.timestamp > withdrawStart, "Not started."); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; aKEEPER.transfer(msg.sender, amount); } function migrate() external { require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract oldaKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; event KeeperRedeemed(address tokenOwner, uint256 amount); event TroveRedeemed(address tokenOwner, uint256 amount); constructor(address _KEEPER, address _aKEEPER, address _staking) { require( _KEEPER != address(0) ); require( _aKEEPER != address(0) ); require( _staking != address(0) ); KEEPER = IERC20(_KEEPER); aKEEPER = IERC20(_aKEEPER); staking = _staking; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } function migrate(uint256 amount) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); KEEPER.transfer(msg.sender, amount); emit KeeperRedeemed(msg.sender, amount); } function migrateTrove(uint256 amount, bool _wrap) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); IERC20( KEEPER ).approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); emit TroveRedeemed(msg.sender, amount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/AggregateV3Interface.sol"; contract aKeeperPresale is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public aKEEPER; address public USDC; address public USDT; address public DAI; address public wBTC; address public gnosisSafe; mapping( address => uint ) public amountInfo; uint deadline; AggregatorV3Interface internal ethPriceFeed; AggregatorV3Interface internal btcPriceFeed; event aKeeperRedeemed(address tokenOwner, uint amount); constructor(address _aKEEPER, address _USDC, address _USDT, address _DAI, address _wBTC, address _ethFeed, address _btcFeed, address _gnosisSafe, uint _deadline) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); require( _USDT != address(0) ); require( _DAI != address(0) ); require( _wBTC != address(0) ); require( _ethFeed != address(0) ); require( _btcFeed != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = _USDC; USDT = _USDT; DAI = _DAI; wBTC = _wBTC; gnosisSafe = _gnosisSafe; deadline = _deadline; ethPriceFeed = AggregatorV3Interface( _ethFeed ); btcPriceFeed = AggregatorV3Interface( _btcFeed ); } function setDeadline(uint _deadline) external onlyOwner() { deadline = _deadline; } function ethAssetPrice() public view returns (int) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return price; } function btcAssetPrice() public view returns (int) { ( , int price, , , ) = btcPriceFeed.latestRoundData(); return price; } function maxAmount() internal pure returns (uint) { return 100000000000; } function getTokens(address principle, uint amount) external { require(block.timestamp < deadline, "Deadline has passed."); require(principle == USDC || principle == USDT || principle == DAI || principle == wBTC, "Token is not acceptable."); require(IERC20(principle).balanceOf(msg.sender) >= amount, "Not enough token amount."); // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount; if (principle == DAI) { aKeeperAmount = amount.div(1e11); } else if (principle == wBTC) { aKeeperAmount = amount.mul(uint(btcAssetPrice())).div(1e9); } else { aKeeperAmount = amount.mul(1e1); } require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); IERC20(principle).safeTransferFrom(msg.sender, gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function getTokensEth() external payable { require(block.timestamp < deadline, "Deadline has passed."); uint amount = msg.value; // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount = amount.mul(uint(ethAssetPrice())).div(1e19); require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); safeTransferETH(gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); require( msg.value == 0 || _amount == msg.value, "Amount should be equal to ETH transferred"); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract aKeeperAirdrop is Ownable { using SafeMath for uint; IERC20 public aKEEPER; IERC20 public USDC; address public gnosisSafe; constructor(address _aKEEPER, address _USDC, address _gnosisSafe) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = IERC20(_USDC); gnosisSafe = _gnosisSafe; } receive() external payable { } function airdropTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { aKEEPER.transfer(_recipients[i], _amounts[i]); } } function refundUsdcTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { USDC.transfer(_recipients[i], _amounts[i]); } } function refundEth(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { safeTransferETH(_recipients[i], _amounts[i]); } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawUsdc() external onlyOwner() { uint256 amount = USDC.balanceOf(address(this)); USDC.transfer(gnosisSafe, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ILPCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ISPV.sol"; import "./interfaces/IStaking.sol"; contract Treasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event DepositEth( uint amount, uint value ); event Sell( address indexed token, uint indexed amount, uint indexed price ); event SellEth( uint indexed amount, uint indexed price ); event ReservesWithdrawn( address indexed caller, address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); event SPVUpdated( address indexed spv ); enum MANAGING { RESERVETOKEN, LIQUIDITYTOKEN, VARIABLETOKEN } struct PriceFeed { address feed; uint decimals; } IKeplerERC20 immutable KEEPER; uint public constant keeperDecimals = 9; uint public immutable priceAdjust; // 4 decimals. 1000 = 0.1 address[] public reserveTokens; mapping( address => bool ) public isReserveToken; address[] public variableTokens; mapping( address => bool ) public isVariableToken; address[] public liquidityTokens; mapping( address => bool ) public isLiquidityToken; mapping( address => address ) public lpCalculator; // bond calculator for liquidity token mapping( address => PriceFeed ) public priceFeeds; // price feeds for variable token uint public totalReserves; uint public spvDebt; uint public daoDebt; uint public ownerDebt; uint public reserveLastAudited; AggregatorV3Interface internal ethPriceFeed; address public staking; address public vesting; address public SPV; address public immutable DAO; uint public daoRatio; // 4 decimals. 1000 = 0.1 uint public spvRatio; // 4 decimals. 7000 = 0.7 uint public vestingRatio; // 4 decimals. 1000 = 0.1 uint public stakeRatio; // 4 decimals. 9000 = 0.9 uint public lcv; // 4 decimals. 1000 = 0.1 uint public keeperSold; uint public initPrice; // To deposit initial reserves when price is undefined (Keeper supply = 0) constructor (address _KEEPER, address _USDC, address _USDT, address _DAI, address _DAO, address _vesting, address _ethPriceFeed, uint _priceAdjust, uint _initPrice) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); require( _DAO != address(0) ); DAO = _DAO; require( _vesting != address(0) ); vesting = _vesting; isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _USDT] = true; reserveTokens.push( _USDT ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); ethPriceFeed = AggregatorV3Interface( _ethPriceFeed ); priceAdjust = _priceAdjust; initPrice = _initPrice; } function treasuryInitialized() external onlyOwner() { initPrice = 0; } function setSPV(address _SPV) external onlyOwner() { require( _SPV != address(0), "Cannot be 0"); SPV = _SPV; emit SPVUpdated( SPV ); } function setVesting(address _vesting) external onlyOwner() { require( _vesting != address(0), "Cannot be 0"); vesting = _vesting; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0), "Cannot be 0"); staking = _staking; } function setLcv(uint _lcv) external onlyOwner() { require( lcv == 0 || _lcv <= lcv.mul(3).div(2), "LCV cannot change sharp" ); lcv = _lcv; } function setTreasuryRatio(uint _daoRatio, uint _spvRatio, uint _vestingRatio, uint _stakeRatio) external onlyOwner() { require( _daoRatio <= 1000, "DAO more than 10%" ); require( _spvRatio <= 7000, "SPV more than 70%" ); require( _vestingRatio <= 2000, "Vesting more than 20%" ); require( _stakeRatio >= 1000 && _stakeRatio <= 10000, "Stake ratio error" ); daoRatio = _daoRatio; spvRatio = _spvRatio; vestingRatio = _vestingRatio; stakeRatio = _stakeRatio; } function getPremium(uint _price) public view returns (uint) { return _price.mul( lcv ).mul( keeperSold ).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ).div( 1e4 ); } function getPrice() public view returns ( uint ) { if (initPrice != 0) { return initPrice; } else { return totalReserves.add(ownerDebt).add( ISPV(SPV).totalValue() ).add( priceAdjust ).mul(10 ** keeperDecimals).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ); } } function ethAssetPrice() public view returns (uint) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 1e8 ); } function variableAssetPrice(address _address, uint _decimals) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface(_address).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** _decimals ); } function EthToUSD( uint _amount ) internal view returns ( uint ) { return _amount.mul( ethAssetPrice() ).div( 1e18 ); } function auditTotalReserves() public { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < variableTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( variableTokens[ i ], IERC20Extended( variableTokens[ i ] ).balanceOf( address(this) ) ) ); } reserves = reserves.add( EthToUSD(address(this).balance) ); totalReserves = reserves; reserveLastAudited = block.timestamp; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice allow depositing an asset for KEEPER @param _amount uint @param _token address @return send_ uint */ function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // IERC20Extended( _token ).safeTransfer( DAO, daoAmount ); uint value = valueOfToken(_token, _amount); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } function depositEth( uint _amount, bool _stake ) external payable returns ( uint send_ ) { require( _amount == msg.value, "Amount should be equal to ETH transferred"); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // safeTransferETH(DAO, daoAmount); uint value = EthToUSD( _amount ); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit DepositEth( _amount, value ); } function sendOrStake(address _recipient, uint _value, bool _stake) internal returns (uint send_) { send_ = _value.mul( 10 ** keeperDecimals ).div( getPrice() ); if ( _stake ) { KEEPER.mint( address(this), send_ ); KEEPER.approve( staking, send_ ); IStaking( staking ).stake( send_, _recipient, false ); } else { KEEPER.mint( _recipient, send_ ); } uint vestingAmount = send_.mul(vestingRatio).div(1e4); KEEPER.mint( vesting, vestingAmount ); } /** @notice allow to burn KEEPER for reserves @param _amount uint of keeper @param _token address */ function sell( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul( 10 ** IERC20Extended( _token ).decimals() ).div( 10 ** keeperDecimals ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); IERC20Extended(_token).safeTransfer(msg.sender, sellAmount); IERC20Extended(_token).safeTransfer(DAO, daoAmount); emit Sell( _token, _amount, sellPrice ); } function sellEth( uint _amount ) external { (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul(10 ** 18).div( ethAssetPrice() ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); safeTransferETH(msg.sender, sellAmount); safeTransferETH(DAO, daoAmount); emit SellEth( _amount, sellPrice ); } function sellKeeperBurn(address _sender, uint _amount) internal returns (uint price, uint premium, uint sellPrice) { price = getPrice(); premium = getPremium(price); sellPrice = price.sub(premium); KEEPER.burnFrom( _sender, _amount ); keeperSold = keeperSold.add( _amount ); uint stakeRewards = _amount.mul(stakeRatio).mul(premium).div(price).div(1e4); KEEPER.mint( address(this), stakeRewards ); KEEPER.approve( staking, stakeRewards ); IStaking( staking ).addRebaseReward( stakeRewards ); } function unstakeMint(uint _amount) external { require( msg.sender == staking, "Not allowed." ); KEEPER.mint(msg.sender, _amount); } function initDeposit( address _token, uint _amount ) external payable onlyOwner() { require( initPrice != 0, "Already initialized" ); uint value; if ( _token == address(0) && msg.value != 0 ) { require( _amount == msg.value, "Amount mismatch" ); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); uint send_ = value.mul( 10 ** keeperDecimals ).div( getPrice() ); KEEPER.mint( msg.sender, send_ ); } /** @notice allow owner multisig to withdraw assets on debt (for safe investments) @param _token address @param _amount uint */ function incurDebt( address _token, uint _amount, bool isEth ) external onlyOwner() { uint value; if ( _token == address(0) && isEth ) { safeTransferETH(msg.sender, _amount); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.sub( value ); ownerDebt = ownerDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( msg.sender, _token, _amount ); } function repayDebt( address _token, uint _amount, bool isEth ) external payable onlyOwner() { uint value; if ( isEth ) { require( msg.value == _amount, "Amount mismatch" ); value = EthToUSD( _amount ); } else { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); if ( value > ownerDebt ) { uint daoProfit = _amount.mul( daoRatio ).mul( value.sub(ownerDebt) ).div( value ).div(1e4); if ( isEth ) { safeTransferETH( DAO, daoProfit ); } else { IERC20Extended( _token ).safeTransfer( DAO, daoProfit ); } value = ownerDebt; } ownerDebt = ownerDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVDeposit( address _token, uint _amount ) external { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken(_token, _amount); totalReserves = totalReserves.add( value ); if ( value > spvDebt ) { value = spvDebt; } spvDebt = spvDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVWithdraw( address _token, uint _amount ) external { require( msg.sender == SPV, "Only SPV" ); address SPVWallet = ISPV( SPV ).SPVWallet(); uint value = valueOfToken(_token, _amount); uint totalValue = totalReserves.add( ISPV(SPV).totalValue() ).add( ownerDebt ); require( spvDebt.add(value) < totalValue.mul(spvRatio).div(1e4), "Debt exceeded" ); spvDebt = spvDebt.add(value); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( SPVWallet, _amount ); } function DAOWithdraw( address _token, uint _amount, bool isEth ) external { require( msg.sender == DAO, "Only DAO Allowed" ); uint value; if ( _token == address(0) && isEth ) { value = EthToUSD( _amount ); } else { value = valueOfToken(_token, _amount); } uint daoProfit = ISPV( SPV ).totalProfit().mul( daoRatio ).div(1e4); require( daoDebt.add(value) <= daoProfit, "Too much" ); if ( _token == address(0) && isEth ) { safeTransferETH(DAO, _amount); } else { IERC20Extended( _token ).safeTransfer( DAO, _amount ); } totalReserves = totalReserves.sub( value ); daoDebt = daoDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( DAO, _token, _amount ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = ILPCalculator( lpCalculator[ _token ] ).valuationUSD( _token, _amount ); } else if ( isVariableToken[ _token ] ) { value_ = _amount.mul(variableAssetPrice( priceFeeds[_token].feed, priceFeeds[_token].decimals )).div( 10 ** IERC20Extended( _token ).decimals() ); } } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculatorFeed address @return bool */ function toggle( MANAGING _managing, address _address, address _calculatorFeed, uint decimals ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVETOKEN ) { // 0 if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 1 if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; lpCalculator[ _address ] = _calculatorFeed; } else if ( _managing == MANAGING.VARIABLETOKEN ) { // 2 if( !listContains( variableTokens, _address ) ) { variableTokens.push( _address ); } result = !isVariableToken[ _address ]; isVariableToken[ _address ] = result; priceFeeds[ _address ] = PriceFeed({ feed: _calculatorFeed, decimals: decimals }); } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains( address[] storage _list, address _token ) internal view returns ( bool ) { for( uint i = 0; i < _list.length; i++ ) { if( _list[ i ] == _token ) { return true; } } return false; } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ILPCalculator { function valuationUSD( address _token, uint _amount ) external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(address account_, uint256 ammount_) external; function burn(uint256 amount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ISPV { function SPVWallet() external view returns ( address ); function totalValue() external view returns ( uint ); function totalProfit() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake(uint _amount, address _recipient, bool _wrap) external; function addRebaseReward( uint _amount ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract aKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; uint public multiplier; // multiplier is 4 decimals i.e. 1000 = 0.1 event KeeperRedeemed(address tokenOwner, uint256 amount); constructor(address _aKEEPER, address _KEEPER, address _staking, uint _multiplier) { require( _aKEEPER != address(0) ); require( _KEEPER != address(0) ); require( _multiplier != 0 ); aKEEPER = IERC20(_aKEEPER); KEEPER = IERC20(_KEEPER); staking = _staking; multiplier = _multiplier; // reduce gas fees of migrate-stake by pre-approving large amount KEEPER.approve( staking, 1e25); } function migrate(uint256 amount, bool _stake, bool _wrap) public { aKEEPER.transferFrom(msg.sender, address(this), amount); uint keeperAmount = amount.mul(multiplier).div(1e4); if ( _stake && staking != address( 0 ) ) { IStaking( staking ).stake( keeperAmount, msg.sender, _wrap ); } else { KEEPER.transfer(msg.sender, keeperAmount); } emit KeeperRedeemed(msg.sender, keeperAmount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract SPV is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event TokenAdded( address indexed token, PRICETYPE indexed priceType, uint indexed price ); event TokenPriceUpdate( address indexed token, uint indexed price ); event TokenPriceTypeUpdate( address indexed token, PRICETYPE indexed priceType ); event TokenRemoved( address indexed token ); event ValueAudited( uint indexed total ); event TreasuryWithdrawn( address indexed token, uint indexed amount ); event TreasuryReturned( address indexed token, uint indexed amount ); uint public constant keeperDecimals = 9; enum PRICETYPE { STABLE, CHAINLINK, UNISWAP, MANUAL } struct TokenPrice { address token; PRICETYPE priceType; uint price; // At keeper decimals } TokenPrice[] public tokens; struct ChainlinkPriceFeed { address feed; uint decimals; } mapping( address => ChainlinkPriceFeed ) public chainlinkPriceFeeds; mapping( address => address ) public uniswapPools; // The other token must be a stablecoin address public immutable treasury; address public SPVWallet; uint public totalValue; uint public totalProfit; uint public spvRecordedValue; uint public recordTime; uint public profitInterval; bool public allowUpdate; // False when SPV is transferring funds constructor (address _treasury, address _USDC, address _USDT, address _DAI, address _SPVWallet, uint _profitInterval) { require( _treasury != address(0) ); treasury = _treasury; require( _SPVWallet != address(0) ); SPVWallet = _SPVWallet; tokens.push(TokenPrice({ token: _USDC, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _USDT, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _DAI, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); recordTime = block.timestamp; require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; spvRecordedValue = 0; allowUpdate = true; updateTotalValue(); } function enableUpdates() external onlyOwner() { allowUpdate = true; } function disableUpdates() external onlyOwner() { allowUpdate = false; } function setInterval( uint _profitInterval ) external onlyOwner() { require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; } function chainlinkTokenPrice(address _token) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface( chainlinkPriceFeeds[_token].feed ).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** chainlinkPriceFeeds[_token].decimals ); } function uniswapTokenPrice(address _token) public view returns (uint) { address _pair = uniswapPools[_token]; ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; address reserveToken; uint tokenAmount; if ( IUniswapV2Pair( _pair ).token0() == _token ) { reserveToken = IUniswapV2Pair( _pair ).token1(); reserve = reserve1; tokenAmount = reserve0; } else { reserveToken = IUniswapV2Pair( _pair ).token0(); reserve = reserve0; tokenAmount = reserve1; } return reserve.mul(10 ** keeperDecimals).mul( 10 ** IERC20Extended(_token).decimals() ).div( tokenAmount ).div( 10 ** IERC20Extended(reserveToken).decimals() ); } function setNewTokenPrice(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) internal returns (uint tokenPrice) { if (_priceType == PRICETYPE.STABLE) { tokenPrice = 10 ** keeperDecimals; } else if (_priceType == PRICETYPE.CHAINLINK) { chainlinkPriceFeeds[_token] = ChainlinkPriceFeed({ feed: _feedOrPool, decimals: _decimals }); tokenPrice = chainlinkTokenPrice(_token); } else if (_priceType == PRICETYPE.UNISWAP) { uniswapPools[_token] = _feedOrPool; tokenPrice = uniswapTokenPrice(_token); } else if (_priceType == PRICETYPE.MANUAL) { tokenPrice = _price; } else { tokenPrice = 0; } } function addToken(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) external onlyOwner() { uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens.push(TokenPrice({ token: _token, priceType: _priceType, price: tokenPrice })); updateTotalValue(); emit TokenAdded(_token, _priceType, tokenPrice); } function updateTokenPrice( uint _index, address _token, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); require( tokens[ _index ].priceType == PRICETYPE.MANUAL, "Only manual tokens can be updated" ); tokens[ _index ].price = _price; updateTotalValue(); emit TokenPriceUpdate(_token, _price); } function updateTokenPriceType( uint _index, address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ].priceType = _priceType; uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens[ _index ].price = tokenPrice; updateTotalValue(); emit TokenPriceTypeUpdate(_token, _priceType); emit TokenPriceUpdate(_token, tokenPrice); } function removeToken( uint _index, address _token ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ] = tokens[tokens.length-1]; tokens.pop(); updateTotalValue(); emit TokenRemoved(_token); } function getTokenBalance( uint _index ) internal view returns (uint) { address _token = tokens[ _index ].token; return IERC20Extended(_token).balanceOf( SPVWallet ).mul(tokens[ _index ].price).div( 10 ** IERC20Extended( _token ).decimals() ); } function auditTotalValue() external { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { PRICETYPE priceType = tokens[i].priceType; if (priceType == PRICETYPE.CHAINLINK) { tokens[i].price = chainlinkTokenPrice(tokens[i].token); } else if (priceType == PRICETYPE.UNISWAP) { tokens[i].price = uniswapTokenPrice(tokens[i].token); } newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; emit ValueAudited(totalValue); } } function calculateProfits() external { require( recordTime.add( profitInterval ) <= block.timestamp, "Not yet" ); require( msg.sender == SPVWallet || msg.sender == ITreasury( treasury ).DAO(), "Not allowed" ); recordTime = block.timestamp; updateTotalValue(); uint currentValue; uint treasuryDebt = ITreasury( treasury ).spvDebt(); if ( treasuryDebt > totalValue ) { currentValue = 0; } else { currentValue = totalValue.sub(treasuryDebt); } if ( currentValue > spvRecordedValue ) { uint profit = currentValue.sub( spvRecordedValue ); spvRecordedValue = currentValue; totalProfit = totalProfit.add(profit); } } function treasuryWithdraw( uint _index, address _token, uint _amount ) external { require( msg.sender == SPVWallet, "Only SPV Wallet allowed" ); require( _token == tokens[ _index ].token, "Wrong token" ); ITreasury( treasury ).SPVWithdraw( _token, _amount ); updateTotalValue(); emit TreasuryWithdrawn( _token, _amount ); } function returnToTreasury( uint _index, address _token, uint _amount ) external { require( _token == tokens[ _index ].token, "Wrong token" ); require( msg.sender == SPVWallet, "Only SPV Wallet can return." ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20Extended( _token ).approve( treasury, _amount ); ITreasury( treasury ).SPVDeposit( _token, _amount ); updateTotalValue(); emit TreasuryReturned( _token, _amount ); } function migrateTokens( address newSPV ) external onlyOwner() { for ( uint i = 0; i < tokens.length; i++ ) { address _token = tokens[ i ].token; IERC20Extended(_token).transfer(newSPV, IERC20Extended(_token).balanceOf( address(this) ) ); } safeTransferETH(newSPV, address(this).balance ); } function updateTotalValue() internal { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function unstakeMint( uint _amount ) external; function SPVDeposit( address _token, uint _amount ) external; function SPVWithdraw( address _token, uint _amount ) external; function DAO() external view returns ( address ); function spvDebt() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract LPCalculator { using SafeMath for uint; address public immutable KEEPER; uint public constant keeperDecimals = 9; constructor ( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function getReserve( address _pair ) public view returns ( address reserveToken, uint reserve ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; reserveToken = IUniswapV2Pair( _pair ).token1(); } else { reserve = reserve0; reserveToken = IUniswapV2Pair( _pair ).token0(); } } function valuationUSD( address _pair, uint _amount ) external view returns ( uint ) { uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); ( address reserveToken, uint reserve ) = getReserve( _pair ); return _amount.mul( reserve ).mul(2).mul( 10 ** keeperDecimals ).div( totalSupply ).div( 10 ** IERC20Extended( reserveToken ).decimals() ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; contract Staking is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; event Stake( address indexed recipient, uint indexed amount, uint indexed timestamp ); event Unstake( address indexed recipient, uint indexed amount, uint indexed timestamp ); uint public constant keeperDecimals = 9; IERC20 public immutable KEEPER; address public immutable treasury; uint public rate; // 6 decimals. 10000 = 0.01 = 1% uint public INDEX; // keeperDecimals decimals uint public keeperRewards; struct Rebase { uint rebaseRate; // 6 decimals uint totalStaked; uint index; uint timeOccured; } struct Epoch { uint number; uint rebaseInterval; uint nextRebase; } Epoch public epoch; Rebase[] public rebases; // past rebase data mapping(address => uint) public stakers; constructor( address _KEEPER, address _treasury, uint _rate, uint _INDEX, uint _rebaseInterval ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); require( _treasury != address(0) ); treasury = _treasury; require( _rate != 0 ); rate = _rate; require( _INDEX != 0 ); INDEX = _INDEX; require( _rebaseInterval != 0 ); epoch = Epoch({ number: 1, rebaseInterval: _rebaseInterval, nextRebase: block.timestamp.add(_rebaseInterval) }); } function setRate( uint _rate ) external onlyOwner() { require( _rate >= rate.div(2) && _rate <= rate.mul(3).div(2), "Rate change cannot be too sharp." ); rate = _rate; } function stake( uint _amount, address _recipient, bool _wrap ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); uint _gonsAmount = getGonsAmount( _amount ); stakers[ _recipient ] = stakers[ _recipient ].add( _gonsAmount ); emit Stake( _recipient, _amount, block.timestamp ); rebase(); } function unstake( uint _amount ) external { rebase(); require( _amount <= stakerAmount(msg.sender), "Cannot unstake more than possible." ); if ( _amount > KEEPER.balanceOf( address(this) ) ) { ITreasury(treasury).unstakeMint( _amount.sub(KEEPER.balanceOf( address(this) ) ) ); } uint gonsAmount = getGonsAmount( _amount ); // Handle math precision error if ( gonsAmount > stakers[msg.sender] ) { gonsAmount = stakers[msg.sender]; } stakers[msg.sender] = stakers[ msg.sender ].sub(gonsAmount); KEEPER.safeTransfer( msg.sender, _amount ); emit Unstake( msg.sender, _amount, block.timestamp ); } function rebase() public { if (epoch.nextRebase <= block.timestamp) { uint rebasingRate = rebaseRate(); INDEX = INDEX.add( INDEX.mul( rebasingRate ).div(1e6) ); epoch.nextRebase = epoch.nextRebase.add(epoch.rebaseInterval); epoch.number++; keeperRewards = 0; rebases.push( Rebase({ rebaseRate: rebasingRate, totalStaked: KEEPER.balanceOf( address(this) ), index: INDEX, timeOccured: block.timestamp }) ); } } function stakerAmount( address _recipient ) public view returns (uint) { return getKeeperAmount(stakers[ _recipient ]); } function rebaseRate() public view returns (uint) { uint keeperBalance = KEEPER.balanceOf( address(this) ); if (keeperBalance == 0) { return rate; } else { return rate.add( keeperRewards.mul(1e6).div( KEEPER.balanceOf( address(this) ) ) ); } } function addRebaseReward( uint _amount ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); keeperRewards = keeperRewards.add( _amount ); } function getGonsAmount( uint _amount ) internal view returns (uint) { return _amount.mul(10 ** keeperDecimals).div(INDEX); } function getKeeperAmount( uint _gons ) internal view returns (uint) { return _gons.mul(INDEX).div(10 ** keeperDecimals); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract MockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract KeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract KeeperVesting is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public immutable KEEPER; event KeeperRedeemed(address redeemer, uint amount); struct Term { uint percent; // 6 decimals % ( 5000 = 0.5% = 0.005 ) uint claimed; } mapping(address => Term) public terms; mapping(address => address) public walletChange; // uint public totalRedeemable; // uint public redeemableLastUpdated; uint public totalRedeemed; // address public redeemUpdater; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); // redeemUpdater = _redeemUpdater; // redeemableLastUpdated = block.timestamp; } // function setRedeemUpdater(address _redeemUpdater) external onlyOwner() { // require( _redeemUpdater != address(0) ); // redeemUpdater = _redeemUpdater; // } // Sets terms for a new wallet function setTerms(address _vester, uint _percent ) external onlyOwner() returns ( bool ) { terms[_vester].percent = _percent; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _percents ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].percent = _percents[i]; } return true; } // function updateTotalRedeemable() external { // require( msg.sender == redeemUpdater, "Only redeem updater can call." ); // uint keeperBalance = KEEPER.balanceOf( address(this) ); // uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000); // totalRedeemable = totalRedeemable.add(newRedeemable); // if (totalRedeemable > keeperBalance ) { // totalRedeemable = keeperBalance; // } // redeemableLastUpdated = block.timestamp; // } // Allows wallet to redeem KEEPER function redeem( uint _amount ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); KEEPER.safeTransfer(msg.sender, _amount); terms[ msg.sender ].claimed = info.claimed.add( _amount ); totalRedeemed = totalRedeemed.add(_amount); emit KeeperRedeemed(msg.sender, _amount); return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].percent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { uint maxRedeemable = KEEPER.balanceOf( address(this) ).add( totalRedeemed ); if ( maxRedeemable > 1e17 ) { maxRedeemable = 1e17; } uint maxRedeemableUser = maxRedeemable.mul( _info.percent ).div(1e6); return maxRedeemableUser.sub(_info.claimed); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; interface KeeperCompatibleInterface { function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); function performUpkeep(bytes calldata performData) external; } interface IStaking { function rebase() external; } interface ITreasury { function auditTotalReserves() external; } interface ISPV { function auditTotalValue() external; } contract DailyUpkeep is KeeperCompatibleInterface, Ownable { /** * Use an interval in seconds and a timestamp to slow execution of Upkeep */ uint public immutable interval; uint public nextTimeStamp; address public staking; address public treasury; address public spv; constructor(address _staking, address _treasury, address _spv, uint _nextTimeStamp, uint _interval) { staking = _staking; treasury = _treasury; spv = _spv; nextTimeStamp = _nextTimeStamp; interval = _interval; } function setStaking(address _staking) external onlyOwner() { staking = _staking; } function setTreasury(address _treasury) external onlyOwner() { treasury = _treasury; } function setSPV(address _spv) external onlyOwner() { spv = _spv; } function checkUpkeep(bytes calldata /* checkData */) external override returns (bool upkeepNeeded, bytes memory /* performData */) { upkeepNeeded = block.timestamp > nextTimeStamp; } function performUpkeep(bytes calldata /* performData */) external override { if (staking != address(0)) { IStaking(staking).rebase(); } if (treasury != address(0)) { ITreasury(treasury).auditTotalReserves(); } if (spv != address(0)) { ISPV(spv).auditTotalValue(); } nextTimeStamp = nextTimeStamp + interval; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldMockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract iKeeperIndexCalculator is Ownable { using SafeMath for uint; event AssetIndexAdded( uint indexed deposit, uint indexed price, address indexed token ); event IndexUpdated( uint indexed fromIndex, uint indexed toIndex, uint oldPrice, uint newPrice ); event DepositUpdated( uint indexed fromDeposit, uint indexed toDeposit ); event AssetIndexWithdrawn( uint indexed deposit, uint price, uint indexed index, address indexed token ); struct AssetIndex { uint deposit; // In USD uint price; // 6 decimals, in USD uint index; // 9 decimals, starts with 1000000000 address token; // Token address of the asset } AssetIndex[] public indices; uint public netIndex; constructor(uint _netIndex) { require( _netIndex != 0, "Index cannot be 0" ); netIndex = _netIndex; } function calculateIndex() public { uint indexProduct = 0; uint totalDeposit = 0; for (uint i=0; i < indices.length; i++) { uint deposit = indices[i].deposit; totalDeposit = totalDeposit.add(deposit); indexProduct = indexProduct.add( indices[i].index.mul( deposit ) ); } netIndex = indexProduct.div(totalDeposit); } function addAssetIndex(uint _deposit, uint _price, address _token) external onlyOwner() { indices.push( AssetIndex({ deposit: _deposit, price: _price, index: 1e9, token: _token })); } function updateIndex(uint _index, address _token, uint _newPrice) external onlyOwner() { AssetIndex storage assetIndex = indices[ _index ]; require(assetIndex.token == _token, "Wrong index."); uint changeIndex = _newPrice.mul(1e9).div(assetIndex.price); uint fromIndex = assetIndex.index; uint oldPrice = assetIndex.price; assetIndex.index = fromIndex.mul(changeIndex).div(1e9); assetIndex.deposit = assetIndex.deposit.mul(changeIndex).div(1e9); assetIndex.price = _newPrice; emit IndexUpdated(fromIndex, assetIndex.index, oldPrice, _newPrice); } function updateDeposit(uint _index, address _token, uint _amount, bool _add) external onlyOwner() { require(_token == indices[ _index ].token, "Wrong index."); uint oldDeposit = indices[ _index ].deposit; require(_add || oldDeposit >= _amount, "Cannot withdraw more than deposit"); if (!_add) { indices[ _index ].deposit = oldDeposit.sub(_amount); } else { indices[ _index ].deposit = oldDeposit.add(_amount); } emit DepositUpdated(oldDeposit, indices[ _index ].deposit); } function withdrawAsset(uint _index, address _token) external onlyOwner() { AssetIndex memory assetIndex = indices[ _index ]; require(_token == assetIndex.token, "Wrong index."); indices[ _index ] = indices[indices.length-1]; indices.pop(); emit AssetIndexWithdrawn(assetIndex.deposit, assetIndex.price, assetIndex.index, assetIndex.token); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IStaking.sol"; // import "./interfaces/IIndexCalculator.sol"; contract iKEEPER is ERC20, Ownable { using SafeMath for uint; address public immutable TROVE; address public immutable staking; address public indexCalculator; constructor(address _TROVE, address _staking, address _indexCalculator) ERC20("Invest KEEPER", "iKEEPER") { require(_TROVE != address(0)); TROVE = _TROVE; require(_staking != address(0)); staking = _staking; require(_indexCalculator != address(0)); indexCalculator = _indexCalculator; } // function setIndexCalculator( address _indexCalculator ) external onlyOwner() { // require( _indexCalculator != address(0) ); // indexCalculator = _indexCalculator; // } // /** // @notice get iKEEPER index (9 decimals) // @return uint // */ // // function getIndex() public view returns (uint) { // // return IIndexCalculator(indexCalculator).netIndex(); // // } // // /** // // @notice wrap KEEPER // // @param _amount uint // // @return uint // // */ // // function wrapKEEPER( uint _amount ) external returns ( uint ) { // // IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); // // uint value = TROVEToiKEEPER( _amount ); // // _mint( msg.sender, value ); // // return value; // // } // /** // @notice wrap TROVE // @param _amount uint // @return uint // */ // function wrap( uint _amount, address _recipient ) external returns ( uint ) { // IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); // uint value = TROVEToiKEEPER( _amount ); // _mint( _recipient, value ); // return value; // } // // /** // // @notice unwrap KEEPER // // @param _amount uint // // @return uint // // */ // // function unwrapKEEPER( uint _amount ) external returns ( uint ) { // // _burn( msg.sender, _amount ); // // uint value = iKEEPERToTROVE( _amount ); // // uint keeperBalance = IERC20(KEEPER).balanceOf( address(this) ); // // if (keeperBalance < value ) { // // uint difference = value.sub(keeperBalance); // // require(IsKEEPER(TROVE).balanceOf(address(this)) >= difference, "Contract does not have enough TROVE"); // // IsKEEPER(TROVE).approve(staking, difference); // // IStaking(staking).unstake(difference, false); // // } // // IERC20( KEEPER ).transfer( msg.sender, value ); // // return value; // // } // /** // @notice unwrap TROVE // @param _amount uint // @return uint // */ // function unwrap( uint _amount ) external returns ( uint ) { // _burn( msg.sender, _amount ); // uint value = iKEEPERToTROVE( _amount ); // IsKEEPER( TROVE ).transfer( msg.sender, value ); // return value; // } // /** // @notice converts iKEEPER amount to TROVE // @param _amount uint // @return uint // */ // function iKEEPERToTROVE( uint _amount ) public view returns ( uint ) { // return _amount.mul( getIndex() ).div( 10 ** decimals() ); // } // /** // @notice converts TROVE amount to iKEEPER // @param _amount uint // @return uint // */ // function TROVEToiKEEPER( uint _amount ) public view returns ( uint ) { // return _amount.mul( 10 ** decimals() ).div( getIndex() ); // } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // intermediate token address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint gonsPayout; // sKEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _wrap bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./libraries/FixedPoint.sol"; interface IBondingCalculator { function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } contract StandardBondingCalculator is IBondingCalculator { using FixedPoint for *; using SafeMath for uint; using SafeMath for uint112; address public immutable KEEPER; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = a.div(2).add(1); while (b < c) { c = b; b = a.div(b).add(b).div(2); } } else if (a != 0) { c = 1; } } function getKValue( address _pair ) public view returns( uint k_ ) { uint token0 = IERC20Extended( IUniswapV2Pair( _pair ).token0() ).decimals(); uint token1 = IERC20Extended( IUniswapV2Pair( _pair ).token1() ).decimals(); (uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint totalDecimals = token0.add( token1 ); uint pairDecimal = IERC20Extended( _pair ).decimals(); if (totalDecimals < pairDecimal) { uint decimals = pairDecimal.sub(totalDecimals); k_ = reserve0.mul(reserve1).mul(10 ** decimals); } else { uint decimals = totalDecimals.sub(pairDecimal); k_ = reserve0.mul(reserve1).div(10 ** decimals); } } function getTotalValue( address _pair ) public view returns ( uint _value ) { _value = sqrrt(getKValue( _pair )).mul(2); } function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) { uint totalValue = getTotalValue( _pair ); uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); _value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 ); } function markdown( address _pair ) external view returns ( uint ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; } else { reserve = reserve0; } return reserve.mul( 2 * ( 10 ** IERC20Extended( KEEPER ).decimals() ) ).div( getTotalValue( _pair ) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract aKEEPER is ERC20 { constructor() ERC20("Alpha Keeper", "aKEEPER") { _setupDecimals(9); _mint(msg.sender, 220000000000000); } function burn(uint256 amount) external { _burn(msg.sender, amount); } }
/ uint daoAmount = _amount.mul(daoRatio).div(1e4); IERC20Extended( _token ).safeTransfer( DAO, daoAmount ); uint daoValue = value.mul(daoRatio).div(1e4); mint KEEPER needed and store amount of rewards for distribution
function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken(_token, _amount); totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); }
12,150,498
// Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.1.0 // 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); } // File contracts/libs/TransferHelper.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // 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,uint)'))); (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,uint)'))); (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,uint)'))); (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 contracts/interfaces/ICoFiXPool.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods and events for CoFiXPool interface ICoFiXPool { /* ****************************************************************************************** * Note: In order to unify the authorization entry, all transferFrom operations are carried * out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and * needs to be taken into account when calculating the pool balance before and after rollover * ******************************************************************************************/ // /// @dev Add liquidity and mining xtoken event // /// @param token Target token address // /// @param to The address to receive xtoken // /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) // /// @param amountToken The amount of Token added to pool // /// @param liquidity The real liquidity or XToken minted from pool // event Mint(address token, address to, uint amountETH, uint amountToken, uint liquidity); // /// @dev Remove liquidity and burn xtoken event // /// @param token The address of ERC20 Token // /// @param to The target address receiving the Token // /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove // /// @param amountETHOut The real amount of ETH transferred from the pool // /// @param amountTokenOut The real amount of Token transferred from the pool // event Burn(address token, address to, uint liquidity, uint amountETHOut, uint amountTokenOut); /// @dev Add liquidity and mint xtoken /// @param token Target token address /// @param to The address to receive xtoken /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function mint( address token, address to, uint amountETH, uint amountToken, address payback ) external payable returns ( address xtoken, uint liquidity ); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// @param token The address of ERC20 Token /// @param to The target address receiving the Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountETHOut The real amount of ETH transferred from the pool /// @return amountTokenOut The real amount of Token transferred from the pool function burn( address token, address to, uint liquidity, address payback ) external payable returns ( uint amountETHOut, uint amountTokenOut ); /// @dev Swap token /// @param src Src token address /// @param dest Dest token address /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountOut The real amount of ETH transferred out of pool /// @return mined The amount of CoFi which will be mind by this trade function swap( address src, address dest, uint amountIn, address to, address payback ) external payable returns ( uint amountOut, uint mined ); /// @dev Gets the token address of the share obtained by the specified token market making /// @param token Target token address /// @return If the fund pool supports the specified token, return the token address of the market share function getXToken(address token) external view returns (address); } // File contracts/interfaces/ICoFiXSinglePool.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 单边池 interface ICoFiXSinglePool is ICoFiXPool { /// @dev Swap for token event /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param amountTokenOut The real amount of token transferred out of pool /// @param mined The amount of CoFi which will be mind by this trade event SwapForToken(uint amountIn, address to, uint amountTokenOut, uint mined); /// @dev Swap for eth event /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param amountETHOut The real amount of eth transferred out of pool /// @param mined The amount of CoFi which will be mind by this trade event SwapForETH(uint amountIn, address to, uint amountETHOut, uint mined); /// @dev Set configuration /// @param theta Trade fee rate, ten thousand points system. 20 /// @param theta0 Trade fee rate for dao, ten thousand points system. 20 /// @param impactCostVOL 将impactCostVOL参数的意义做出调整,表示冲击成本倍数 function setConfig(uint16 theta, uint16 theta0, uint96 impactCostVOL) external; /// @dev Get configuration /// @return theta Trade fee rate, ten thousand points system. 20 /// @return theta0 Trade fee rate for dao, ten thousand points system. 20 /// @return impactCostVOL 将impactCostVOL参数的意义做出调整,表示冲击成本倍数 function getConfig() external view returns (uint16 theta, uint16 theta0, uint96 impactCostVOL); /// @dev Settle trade fee to DAO function settle() external; /// @dev Get eth balance of this pool /// @return eth balance of this pool function ethBalance() external view returns (uint); /// @dev Get total trade fee which not settled function totalFee() external view returns (uint); /// @dev Get net worth /// @param ethAmount Oracle price - eth amount /// @param tokenAmount Oracle price - token amount /// @return navps Net worth function getNAVPerShare( uint ethAmount, uint tokenAmount ) external view returns (uint navps); /// @dev Calculate the impact cost of buy in eth /// @param vol Trade amount in eth /// @return impactCost Impact cost function impactCostForBuyInETH(uint vol) external view returns (uint impactCost); /// @dev Calculate the impact cost of sell out eth /// @param vol Trade amount in eth /// @return impactCost Impact cost function impactCostForSellOutETH(uint vol) external view returns (uint impactCost); } // File contracts/interfaces/INestPriceFacade.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the methods for price call entry interface INestPriceFacade { // /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @param flag Address flag // function setAddressFlag(address addr, uint flag) external; // /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @return Address flag // function getAddressFlag(address addr) external view returns(uint); // /// @dev Set INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @param nestQueryAddress INestQuery implementation contract address, 0 means delete // function setNestQuery(address tokenAddress, address nestQueryAddress) external; // /// @dev Get INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @return INestQuery implementation contract address, 0 means use default // function getNestQuery(address tokenAddress) external view returns (address); // /// @dev Get the latest trigger price // /// @param tokenAddress Destination token address // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function triggeredPrice(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price); // /// @dev Get the full information of latest trigger price // /// @param tokenAddress Destination token address // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return avgPrice Average price // /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that // /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, // /// it means that the volatility has exceeded the range that can be expressed // function triggeredPriceInfo(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ); // /// @dev Find the price at block number // /// @param tokenAddress Destination token address // /// @param height Destination block number // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function findPrice(address tokenAddress, uint height, address payback) external payable returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price); // /// @dev Get the last (num) effective price // /// @param tokenAddress Destination token address // /// @param count The number of prices that want to return // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price // function lastPriceList(address tokenAddress, uint count, address payback) external payable returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress, address payback) external payable returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo( address tokenAddress, uint count, address payback ) external payable returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); // /// @dev Get the latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function triggeredPrice2(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice); // /// @dev Get the full information of latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return avgPrice Average price // /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that // /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, // /// it means that the volatility has exceeded the range that can be expressed // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // /// @return ntokenAvgPrice Average price of ntoken // /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that // /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, // /// it means that the volatility has exceeded the range that can be expressed // function triggeredPriceInfo2(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ); // /// @dev Get the latest effective price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function latestPrice2(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice); } // File contracts/interfaces/ICoFiXController.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the methods for price call entry interface ICoFiXController { // Calc variance of price and K in CoFiX is very expensive // We use expected value of K based on statistical calculations here to save gas // In the near future, NEST could provide the variance of price directly. We will adopt it then. // We can make use of `data` bytes in the future /// @dev Query price /// @param tokenAddress Target address of token /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return ethAmount Oracle price - eth amount /// @return tokenAmount Oracle price - token amount /// @return blockNumber Block number of price function queryPrice( address tokenAddress, address payback ) external payable returns ( uint ethAmount, uint tokenAmount, uint blockNumber ); /// @dev Calc variance of price and K in CoFiX is very expensive /// We use expected value of K based on statistical calculations here to save gas /// In the near future, NEST could provide the variance of price directly. We will adopt it then. /// We can make use of `data` bytes in the future /// @param tokenAddress Target address of token /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return k The K value(18 decimal places). /// @return ethAmount Oracle price - eth amount /// @return tokenAmount Oracle price - token amount /// @return blockNumber Block number of price function queryOracle( address tokenAddress, address payback ) external payable returns ( uint k, uint ethAmount, uint tokenAmount, uint blockNumber ); /// @dev K value is calculated by revised volatility /// @param sigmaSQ The square of the volatility (18 decimal places). /// @param p0 Last price (number of tokens equivalent to 1 ETH) /// @param bn0 Block number of the last price /// @param p Latest price (number of tokens equivalent to 1 ETH) /// @param bn The block number when (ETH, TOKEN) price takes into effective function calcRevisedK(uint sigmaSQ, uint p0, uint bn0, uint p, uint bn) external view returns (uint k); /// @dev Query latest price info /// @param tokenAddress Target address of token /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber Block number of price /// @return priceEthAmount Oracle price - eth amount /// @return priceTokenAmount Oracle price - token amount /// @return avgPriceEthAmount Avg price - eth amount /// @return avgPriceTokenAmount Avg price - token amount /// @return sigmaSQ The square of the volatility (18 decimal places) function latestPriceInfo(address tokenAddress, address payback) external payable returns ( uint blockNumber, uint priceEthAmount, uint priceTokenAmount, uint avgPriceEthAmount, uint avgPriceTokenAmount, uint sigmaSQ ); } // File contracts/interfaces/ICoFiXDAO.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the DAO methods interface ICoFiXDAO { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of CoFiXDAO contract struct Config { // Redeem status, 1 means normal uint8 status; // The number of CoFi redeem per block. 100 uint16 cofiPerBlock; // The maximum number of CoFi in a single redeem. 30000 uint32 cofiLimit; // Price deviation limit, beyond this upper limit stop redeem (10000 based). 1000 uint16 priceDeviationLimit; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Set the exchange relationship between the token and the price of the anchored target currency. /// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places. /// so exchange = 1e6 * 1 ether / 1e18 = 1e6 /// @param token Address of origin token /// @param target Address of target anchor token /// @param exchange Exchange rate of token and target function setTokenExchange(address token, address target, uint exchange) external; /// @dev Get the exchange relationship between the token and the price of the anchored target currency. /// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places. /// so exchange = 1e6 * 1 ether / 1e18 = 1e6 /// @param token Address of origin token /// @return target Address of target anchor token /// @return exchange Exchange rate of token and target function getTokenExchange(address token) external view returns (address target, uint exchange); /// @dev Add reward /// @param pool Destination pool function addETHReward(address pool) external payable; /// @dev The function returns eth rewards of specified pool /// @param pool Destination pool function totalETHRewards(address pool) external view returns (uint); /// @dev Settlement /// @param pool Destination pool. Indicates which pool to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address pool, address tokenAddress, address to, uint value) external payable; /// @dev Redeem CoFi for ethers /// @notice Eth fee will be charged /// @param amount The amount of CoFi /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address function redeem(uint amount, address payback) external payable; /// @dev Redeem CoFi for Token /// @notice Eth fee will be charged /// @param token The target token /// @param amount The amount of CoFi /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address function redeemToken(address token, uint amount, address payback) external payable; /// @dev Get the current amount available for repurchase function quotaOf() external view returns (uint); } // File contracts/interfaces/ICoFiXMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for CoFiX builtin contract address mapping interface ICoFiXMapping { /// @dev Set the built-in contract address of the system /// @param cofiToken Address of CoFi token contract /// @param cofiNode Address of CoFi Node contract /// @param cofixDAO ICoFiXDAO implementation contract address /// @param cofixRouter ICoFiXRouter implementation contract address for CoFiX /// @param cofixController ICoFiXController implementation contract address /// @param cofixVaultForStaking ICoFiXVaultForStaking implementation contract address function setBuiltinAddress( address cofiToken, address cofiNode, address cofixDAO, address cofixRouter, address cofixController, address cofixVaultForStaking ) external; /// @dev Get the built-in contract address of the system /// @return cofiToken Address of CoFi token contract /// @return cofiNode Address of CoFi Node contract /// @return cofixDAO ICoFiXDAO implementation contract address /// @return cofixRouter ICoFiXRouter implementation contract address for CoFiX /// @return cofixController ICoFiXController implementation contract address function getBuiltinAddress() external view returns ( address cofiToken, address cofiNode, address cofixDAO, address cofixRouter, address cofixController, address cofixVaultForStaking ); /// @dev Get address of CoFi token contract /// @return Address of CoFi Node token contract function getCoFiTokenAddress() external view returns (address); /// @dev Get address of CoFi Node contract /// @return Address of CoFi Node contract function getCoFiNodeAddress() external view returns (address); /// @dev Get ICoFiXDAO implementation contract address /// @return ICoFiXDAO implementation contract address function getCoFiXDAOAddress() external view returns (address); /// @dev Get ICoFiXRouter implementation contract address for CoFiX /// @return ICoFiXRouter implementation contract address for CoFiX function getCoFiXRouterAddress() external view returns (address); /// @dev Get ICoFiXController implementation contract address /// @return ICoFiXController implementation contract address function getCoFiXControllerAddress() external view returns (address); /// @dev Get ICoFiXVaultForStaking implementation contract address /// @return ICoFiXVaultForStaking implementation contract address function getCoFiXVaultForStakingAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by CoFiX system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string calldata key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string calldata key) external view returns (address); } // File contracts/interfaces/ICoFiXGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface ICoFiXGovernance is ICoFiXMapping { /// @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 contracts/CoFiXBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // Router contract to interact with each CoFiXPair, no owner or governance /// @dev Base contract of CoFiX contract CoFiXBase { // // Address of CoFiToken contract address constant COFI_TOKEN_ADDRESS = 0x1a23a6BfBAdB59fa563008c0fB7cf96dfCF34Ea1; // // Address of CoFiNode contract address constant CNODE_TOKEN_ADDRESS = 0x558201DC4741efc11031Cdc3BC1bC728C23bF512; // Genesis block number of CoFi // CoFiToken contract is created at block height 11040156. However, because the mining algorithm of CoFiX1.0 // is different from that at present, a new mining algorithm is adopted from CoFiX2.1. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the CoFi begins to decay. According to the circulation when CoFi2.0 is online, the new mining // algorithm is used to deduce and convert the CoFi, and the new algorithm is used to mine the CoFiX2.1 // on-line flow, the actual block is 11040688 uint constant COFI_GENESIS_BLOCK = 11040688; /// @dev ICoFiXGovernance implementation contract address address public _governance; /// @dev To support open-zeppelin/upgrades /// @param governance ICoFiXGovernance implementation contract address function initialize(address governance) public virtual { require(_governance == address(0), "CoFiX:!initialize"); _governance = 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 ICoFiXGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || ICoFiXGovernance(governance).checkGovernance(msg.sender, 0), "CoFiX:!gov"); _governance = newGovernance; } /// @dev Migrate funds from current contract to CoFiXDAO /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = ICoFiXGovernance(_governance).getCoFiXDAOAddress(); if (tokenAddress == address(0)) { ICoFiXDAO(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(ICoFiXGovernance(_governance).checkGovernance(msg.sender, 0), "CoFiX:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "CoFiX:!contract"); _; } } // File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v4.1.0 // MIT pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/Context.sol@v4.1.0 // 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; } } // File @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.1.0 // MIT pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/CoFiToken.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // CoFiToken with Governance. It offers possibilities to adopt off-chain gasless governance infra. contract CoFiToken is ERC20("CoFi Token", "CoFi") { address public governance; mapping (address => bool) public minters; // Copied and modified from SUSHI code: // https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol // Which is copied and modified from YAM code and COMPOUND: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @dev An event thats emitted when a new governance account is set /// @param _new The new governance address event NewGovernance(address _new); /// @dev An event thats emitted when a new minter account is added /// @param _minter The new minter address added event MinterAdded(address _minter); /// @dev An event thats emitted when a minter account is removed /// @param _minter The minter address removed event MinterRemoved(address _minter); modifier onlyGovernance() { require(msg.sender == governance, "CoFi: !governance"); _; } constructor() { governance = msg.sender; } function setGovernance(address _new) external onlyGovernance { require(_new != address(0), "CoFi: zero addr"); require(_new != governance, "CoFi: same addr"); governance = _new; emit NewGovernance(_new); } function addMinter(address _minter) external onlyGovernance { minters[_minter] = true; emit MinterAdded(_minter); } function removeMinter(address _minter) external onlyGovernance { minters[_minter] = false; emit MinterRemoved(_minter); } /// @notice mint is used to distribute CoFi token to users, minters are CoFi mining pools function mint(address _to, uint _amount) external { require(minters[msg.sender], "CoFi: !minter"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice SUSHI has a vote governance bug in its token implementation, CoFi fixed it here /// read https://blog.peckshield.com/2020/09/08/sushi/ function transfer(address _recipient, uint _amount) public override returns (bool) { super.transfer(_recipient, _amount); _moveDelegates(_delegates[msg.sender], _delegates[_recipient], _amount); return true; } /// @notice override original transferFrom to fix vote issue function transferFrom(address _sender, address _recipient, uint _amount) public override returns (bool) { super.transferFrom(_sender, _recipient, _amount); _moveDelegates(_delegates[_sender], _delegates[_recipient], _amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CoFi::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CoFi::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "CoFi::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint) { require(blockNumber < block.number, "CoFi::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint delegatorBalance = balanceOf(delegator); // balance of underlying CoFis (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld - (amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld + (amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes ) internal { uint32 blockNumber = safe32(block.number, "CoFi::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } // File contracts/interfaces/ICoFiXERC20.sol // GPL-3.0-or-later pragma solidity ^0.8.6; interface ICoFiXERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); // function name() external pure returns (string memory); // function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); // function DOMAIN_SEPARATOR() external view returns (bytes32); // function PERMIT_TYPEHASH() external pure returns (bytes32); // function nonces(address owner) external view returns (uint); // function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // File contracts/CoFiXERC20.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // ERC20 token implementation, inherited by CoFiXPair contract, no owner or governance contract CoFiXERC20 is ICoFiXERC20 { //string public constant nameForDomain = 'CoFiX Pool Token'; uint8 public override constant decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; //bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); //bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; //mapping(address => uint) public override nonces; //event Approval(address indexed owner, address indexed spender, uint value); //event Transfer(address indexed from, address indexed to, uint value); constructor() { // uint chainId; // assembly { // chainId := chainid() // } // DOMAIN_SEPARATOR = keccak256( // abi.encode( // keccak256('EIP712Domain(string name,string version,uint chainId,address verifyingContract)'), // keccak256(bytes(nameForDomain)), // keccak256(bytes('1')), // chainId, // address(this) // ) // ); } function _mint(address to, uint value) internal { totalSupply = totalSupply + (value); balanceOf[to] = balanceOf[to] + (value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from] - (value); totalSupply = totalSupply - (value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from] - (value); balanceOf[to] = balanceOf[to] + (value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { allowance[from][msg.sender] = allowance[from][msg.sender] - (value); } _transfer(from, to, value); return true; } // function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { // require(deadline >= block.timestamp, 'CERC20: EXPIRED'); // bytes32 digest = keccak256( // abi.encodePacked( // '\x19\x01', // DOMAIN_SEPARATOR, // keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) // ) // ); // address recoveredAddress = ecrecover(digest, v, r, s); // require(recoveredAddress != address(0) && recoveredAddress == owner, 'CERC20: INVALID_SIGNATURE'); // _approve(owner, spender, value); // } } // File contracts/CoFiXSinglePool.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 单边池 contract CoFiXSinglePool is CoFiXBase, CoFiXERC20, ICoFiXSinglePool { /* ****************************************************************************************** * Note: In order to unify the authorization entry, all transferFrom operations are carried * out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and * needs to be taken into account when calculating the pool balance before and after rollover * ******************************************************************************************/ // it's negligible because we calc liquidity in ETH uint constant MINIMUM_LIQUIDITY = 1e9; // Target token address address _tokenAddress; // Trade fee rate, ten thousand points system. 20 uint16 _theta; // Trade fee rate for dao, ten thousand points system. 20 uint16 _theta0; // ERC20 - name string public name; // ERC20 - symbol string public symbol; // Address of CoFiXDAO address _cofixDAO; // Address of CoFiXRouter address _cofixRouter; // Lock flag bool _locked; // Total trade fee uint72 _totalFee; // Address of CoFiXController address _cofixController; // Impact cost threshold, this parameter is obsolete // 将_impactCostVOL参数的意义做出调整,表示冲击成本倍数 // 冲击成本计算公式:vol * uint(_impactCostVOL) * 0.00001 uint96 _impactCostVOL; // Constructor, in order to support openzeppelin's scalable scheme, // it's need to move the constructor to the initialize method constructor() { } /// @dev init Initialize /// @param governance ICoFiXGovernance implementation contract address /// @param name_ Name of xtoken /// @param symbol_ Symbol of xtoken /// @param tokenAddress Target token address function init( address governance, string calldata name_, string calldata symbol_, address tokenAddress ) external { super.initialize(governance); name = name_; symbol = symbol_; _tokenAddress = tokenAddress; } modifier check() { require(_cofixRouter == msg.sender, "CoFiXPair: Only for CoFiXRouter"); require(!_locked, "CoFiXPair: LOCKED"); _locked = true; _; _locked = false; } /// @dev Set configuration /// @param theta Trade fee rate, ten thousand points system. 20 /// @param theta0 Trade fee rate for dao, ten thousand points system. 20 /// @param impactCostVOL 将impactCostVOL参数的意义做出调整,表示冲击成本倍数 function setConfig(uint16 theta, uint16 theta0, uint96 impactCostVOL) external override onlyGovernance { // Trade fee rate, ten thousand points system. 20 _theta = theta; // Trade fee rate for dao, ten thousand points system. 20 _theta0 = theta0; // 将impactCostVOL参数的意义做出调整,表示冲击成本倍数 _impactCostVOL = impactCostVOL; } /// @dev Get configuration /// @return theta Trade fee rate, ten thousand points system. 20 /// @return theta0 Trade fee rate for dao, ten thousand points system. 20 /// @return impactCostVOL 将impactCostVOL参数的意义做出调整,表示冲击成本倍数 function getConfig() external view override returns (uint16 theta, uint16 theta0, uint96 impactCostVOL) { return (_theta, _theta0, _impactCostVOL); } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance ICoFiXGovernance implementation contract address function update(address newGovernance) public override { super.update(newGovernance); ( ,//cofiToken, ,//cofiNode, _cofixDAO, _cofixRouter, _cofixController, //cofixVaultForStaking ) = ICoFiXGovernance(newGovernance).getBuiltinAddress(); } /// @dev Add liquidity and mint xtoken /// @param token Target token address /// @param to The address to receive xtoken /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function mint( address token, address to, uint amountETH, uint amountToken, address payback ) external payable override check returns ( address xtoken, uint liquidity ) { // 1. Check token address require(token == _tokenAddress, "CoFiXPair: invalid token address"); // 2. Calculate net worth and share uint total = totalSupply; // 3. Query oracle ( uint k, uint ethAmount, uint tokenAmount, //uint blockNumber, ) = ICoFiXController(_cofixController).queryOracle { value: msg.value - amountETH } ( token, payback ); tokenAmount = tokenAmount * (1 ether + k) / 1 ether; liquidity = amountETH + amountToken * ethAmount / tokenAmount; if (total > 0) { uint balance0 = ethBalance(); uint balance1 = IERC20(token).balanceOf(address(this)); liquidity = liquidity * total / _calcTotalValue( // To calculate the net value, we need to use the asset balance before the market making fund // is transferred. Since the ETH was transferred when CoFiXRouter called this method and the // Token was transferred before CoFiXRouter called this method, we need to deduct the amountETH // and amountToken respectively // The current eth balance minus the amount eth equals the ETH balance before the transaction balance0 - amountETH, //The current token balance minus the amountToken equals to the token balance before the transaction balance1 - amountToken, // Oracle price - eth amount ethAmount, // Oracle price - token amount tokenAmount ); } else { _mint(address(0), MINIMUM_LIQUIDITY); liquidity -= MINIMUM_LIQUIDITY; } // 5. Increase xtoken _mint(to, liquidity); //emit Mint(token, to, amountETH, amountToken, liquidity); xtoken = address(this); } /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// @param token The address of ERC20 Token /// @param to The target address receiving the Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountETHOut The real amount of ETH transferred from the pool /// @return amountTokenOut The real amount of Token transferred from the pool function burn( address token, address to, uint liquidity, address payback ) external payable override check returns ( uint amountETHOut, uint amountTokenOut ) { if(msg.value > 0) { payable(payback).transfer(msg.value); } // 1. Check token address require(token == _tokenAddress, "CoFiXPair: invalid token address"); // 3. Calculate the net value and calculate the equal proportion fund according to the net value uint balance0 = ethBalance(); uint balance1 = IERC20(token).balanceOf(address(this)); uint total = totalSupply; amountETHOut = balance0 * liquidity / total; amountTokenOut = balance1 * liquidity / total; // 5. Destroy xtoken _burn(address(this), liquidity); //emit Burn(token, to, liquidity, amountETHOut, amountTokenOut); // 7. Transfer of funds to the user's designated address payable(to).transfer(amountETHOut); TransferHelper.safeTransfer(token, to, amountTokenOut); } /// @dev Swap token /// @param src Src token address /// @param dest Dest token address /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountOut The real amount of ETH transferred out of pool /// @return mined The amount of CoFi which will be mind by this trade function swap( address src, address dest, uint amountIn, address to, address payback ) external payable override check returns ( uint amountOut, uint mined ) { address token = _tokenAddress; if (src == address(0) && dest == token) { (amountOut, mined) = _swapForToken(token, amountIn, to, payback); } else if (src == token && dest == address(0)) { (amountOut, mined) = _swapForETH(token, amountIn, to, payback); } else { revert("CoFiXPair: pair error"); } } /// @dev Swap for tokens /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountTokenOut The real amount of token transferred out of pool /// @return mined The amount of CoFi which will be mind by this trade function _swapForToken( address token, uint amountIn, address to, address payback ) private returns ( uint amountTokenOut, uint mined ) { // 1. Query oracle ( uint k, uint ethAmount, uint tokenAmount, //uint blockNumber, ) = ICoFiXController(_cofixController).queryOracle { value: msg.value - amountIn } ( token, payback ); // 2. Calculate the trade result uint theta = uint(_theta); uint fee = amountIn * theta / 10000; amountTokenOut = (amountIn - fee) * tokenAmount * 1 ether / ethAmount / ( 1 ether + k + impactCostForSellOutETH(amountIn) ); // 3. Transfer transaction fee fee = _collect(fee * uint(_theta0) / theta); // 5. Transfer token TransferHelper.safeTransfer(token, to, amountTokenOut); emit SwapForToken(amountIn, to, amountTokenOut, mined); } /// @dev Swap for eth /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountETHOut The real amount of eth transferred out of pool /// @return mined The amount of CoFi which will be mind by this trade function _swapForETH( address token, uint amountIn, address to, address payback ) private returns ( uint amountETHOut, uint mined ) { // 1. Query oracle ( uint k, uint ethAmount, uint tokenAmount, //uint blockNumber, ) = ICoFiXController(_cofixController).queryOracle { value: msg.value } ( token, payback ); // 2. Calculate the trade result amountETHOut = amountIn * ethAmount / tokenAmount; amountETHOut = amountETHOut * 1 ether / ( 1 ether + k + impactCostForBuyInETH(amountETHOut) ); uint theta = uint(_theta); uint fee = amountETHOut * theta / 10000; amountETHOut = amountETHOut - fee; // 3. Transfer transaction fee fee = _collect(fee * uint(_theta0) / theta); // 5. Transfer token payable(to).transfer(amountETHOut); emit SwapForETH(amountIn, to, amountETHOut, mined); } // Deposit transaction fee function _collect(uint fee) private returns (uint total) { // 佣金的1/3进入DAO,2/3留在资金池 total = uint(_totalFee) + fee; if (total >= 1 ether) { ICoFiXDAO(_cofixDAO).addETHReward { value: total } (address(this)); total = 0; } _totalFee = uint72(total); } /// @dev Settle trade fee to DAO function settle() external override { ICoFiXDAO(_cofixDAO).addETHReward { value: uint(_totalFee) } (address(this)); _totalFee = uint72(0); } /// @dev Get eth balance of this pool /// @return eth balance of this pool function ethBalance() public view override returns (uint) { return address(this).balance - uint(_totalFee); } /// @dev Get total trade fee which not settled function totalFee() external view override returns (uint) { return uint(_totalFee); } /// @dev Get net worth /// @param ethAmount Oracle price - eth amount /// @param tokenAmount Oracle price - token amount /// @return navps Net worth function getNAVPerShare( uint ethAmount, uint tokenAmount ) external view override returns (uint navps) { // 做市: Np = (Au * (1 + K) / P + Ae) / S uint total = totalSupply; navps = total > 0 ? _calcTotalValue( ethBalance(), IERC20(_tokenAddress).balanceOf(address(this)), ethAmount, tokenAmount ) * 1 ether / total : 1 ether; } // Calculate the total value of asset balance function _calcTotalValue( uint balance0, uint balance1, uint ethAmount, uint tokenAmount ) private pure returns (uint totalValue) { totalValue = balance0 + balance1 * ethAmount / tokenAmount; } /// @dev Calculate the impact cost of buy in eth /// @param vol Trade amount in eth /// @return impactCost Impact cost function impactCostForBuyInETH(uint vol) public view override returns (uint impactCost) { //return _impactCostForBuyInETH(vol, uint(_impactCostVOL)); impactCost = vol * uint(_impactCostVOL) / 100000; } /// @dev Calculate the impact cost of sell out eth /// @param vol Trade amount in eth /// @return impactCost Impact cost function impactCostForSellOutETH(uint vol) public view override returns (uint impactCost) { //return _impactCostForSellOutETH(vol, uint(_impactCostVOL)); impactCost = vol * uint(_impactCostVOL) / 100000; } /// @dev Gets the token address of the share obtained by the specified token market making /// @param token Target token address /// @return If the fund pool supports the specified token, return the token address of the market share function getXToken(address token) external view override returns (address) { if (token == _tokenAddress) { return address(this); } return address(0); } }
This interface defines methods and events for CoFiXPool / Add liquidity and mining xtoken event / token Target token address / to The address to receive xtoken / amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) / amountToken The amount of Token added to pool / liquidity The real liquidity or XToken minted from pool event Mint(address token, address to, uint amountETH, uint amountToken, uint liquidity); / Remove liquidity and burn xtoken event / token The address of ERC20 Token / to The target address receiving the Token / liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove / amountETHOut The real amount of ETH transferred from the pool / amountTokenOut The real amount of Token transferred from the pool event Burn(address token, address to, uint liquidity, uint amountETHOut, uint amountTokenOut);
interface ICoFiXPool { function mint( address token, address to, uint amountETH, uint amountToken, address payback ) external payable returns ( address xtoken, uint liquidity ); function burn( address token, address to, uint liquidity, address payback ) external payable returns ( uint amountETHOut, uint amountTokenOut ); function swap( address src, address dest, uint amountIn, address to, address payback ) external payable returns ( uint amountOut, uint mined ); function getXToken(address token) external view returns (address); }
7,018,455
./partial_match/1/0x6D061EBFd8BDF5D574A7029E918341B1736d6F6c/sources/SmolTingPot.sol
as this token is non tradable, only minters are allowed to transfer tokens between accounts
function transferFrom(address owner, address buyer, uint numTokens) public onlyCanTransfer returns (bool) { require(numTokens <= _balances[owner]); _balances[owner] = _balances[owner].sub(numTokens); _balances[buyer] = _balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true; }
3,893,426
./full_match/80001/0xB44Ae12e3245A3FbdD9445c536ef568a702e77DF/sources/contracts/Skybet.sol
Function to check if a token exists _symbol Symbol of the token to be checked
function tokenExists( string memory _symbol ) internal view returns (bool exists) { for (uint i = 0; i < tokenCount; i++) { if (keccak256(bytes(_symbol)) == keccak256(bytes(Tokens[i].symbol))) { return true; } } return false; }
845,130
pragma solidity ^0.5.8; contract ERC20Interface { function NAME619() public view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL529() public view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS264() public view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY200() public view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF986(address tokenOwner) public view returns (uint balance); //inject NONSTANDARD NAMING function ALLOWANCE990(address tokenOwner, address spender) public view returns (uint remaining); //inject NONSTANDARD NAMING function TRANSFER909(address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function APPROVE745(address spender, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM849(address from, address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function BURN943(uint256 amount) public; //inject NONSTANDARD NAMING event TRANSFER421(address indexed from, address indexed to, uint tokens); //inject NONSTANDARD NAMING event APPROVAL99(address indexed tokenOwner, address indexed spender, uint tokens); //inject NONSTANDARD NAMING } contract MerkleDrop { bytes32 public root; ERC20Interface public droppedToken; uint public decayStartTime; uint public decayDurationInSeconds; uint public initialBalance; uint public remainingValue; // The total of not withdrawn entitlements, not considering decay uint public spentTokens; // The total tokens spent by the contract, burnt or withdrawn mapping (address => bool) public withdrawn; event WITHDRAW776(address recipient, uint value, uint originalValue); //inject NONSTANDARD NAMING event BURN575(uint value); //inject NONSTANDARD NAMING constructor(ERC20Interface _droppedToken, uint _initialBalance, bytes32 _root, uint _decayStartTime, uint _decayDurationInSeconds) public { // The _initialBalance should be equal to the sum of airdropped tokens droppedToken = _droppedToken; initialBalance = _initialBalance; remainingValue = _initialBalance; root = _root; decayStartTime = _decayStartTime; decayDurationInSeconds = _decayDurationInSeconds; } function WITHDRAW337(uint value, bytes32[] memory proof) public { //inject NONSTANDARD NAMING require(VERIFYENTITLED968(msg.sender, value, proof), "The proof could not be verified."); require(! withdrawn[msg.sender], "You have already withdrawn your entitled token."); BURNUNUSABLETOKENS848(); uint valueToSend = DECAYEDENTITLEMENTATTIME410(value, now, false); assert(valueToSend <= value); require(droppedToken.BALANCEOF986(address(this)) >= valueToSend, "The MerkleDrop does not have tokens to drop yet / anymore."); require(valueToSend != 0, "The decayed entitled value is now zero."); withdrawn[msg.sender] = true; remainingValue -= value; spentTokens += valueToSend; require(droppedToken.TRANSFER909(msg.sender, valueToSend)); emit WITHDRAW776(msg.sender, valueToSend, value); } function VERIFYENTITLED968(address recipient, uint value, bytes32[] memory proof) public view returns (bool) { //inject NONSTANDARD NAMING // We need to pack the 20 bytes address to the 32 bytes value // to match with the proof made with the python merkle-drop package bytes32 leaf = keccak256(abi.encodePacked(recipient, value)); return VERIFYPROOF104(leaf, proof); } function DECAYEDENTITLEMENTATTIME410(uint value, uint time, bool roundUp) public view returns (uint) { //inject NONSTANDARD NAMING if (time <= decayStartTime) { return value; } else if (time >= decayStartTime + decayDurationInSeconds) { return 0; } else { uint timeDecayed = time - decayStartTime; uint valueDecay = DECAY452(value, timeDecayed, decayDurationInSeconds, !roundUp); assert(valueDecay <= value); return value - valueDecay; } } function BURNUNUSABLETOKENS848() public { //inject NONSTANDARD NAMING if (now <= decayStartTime) { return; } // The amount of tokens that should be held within the contract after burning uint targetBalance = DECAYEDENTITLEMENTATTIME410(remainingValue, now, true); // toBurn = (initial balance - target balance) - what we already removed from initial balance uint currentBalance = initialBalance - spentTokens; assert(targetBalance <= currentBalance); uint toBurn = currentBalance - targetBalance; spentTokens += toBurn; BURN943(toBurn); } function DELETECONTRACT939() public { //inject NONSTANDARD NAMING require(now >= decayStartTime + decayDurationInSeconds, "The storage cannot be deleted before the end of the merkle drop."); BURNUNUSABLETOKENS848(); selfdestruct(address(0)); } function VERIFYPROOF104(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 currentHash = leaf; for (uint i = 0; i < proof.length; i += 1) { currentHash = PARENTHASH659(currentHash, proof[i]); } return currentHash == root; } function PARENTHASH659(bytes32 a, bytes32 b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING if (a < b) { return keccak256(abi.encode(a, b)); } else { return keccak256(abi.encode(b, a)); } } function BURN943(uint value) internal { //inject NONSTANDARD NAMING if (value == 0) { return; } emit BURN575(value); droppedToken.BURN943(value); } function DECAY452(uint value, uint timeToDecay, uint totalDecayTime, bool roundUp) internal pure returns (uint) { //inject NONSTANDARD NAMING uint decay; if (roundUp) { decay = (value*timeToDecay+totalDecayTime-1)/totalDecayTime; } else { decay = value*timeToDecay/totalDecayTime; } return decay >= value ? value : decay; } }
inject NONSTANDARD NAMING
function BURN943(uint value) internal {
12,727,517
./full_match/1/0x627a25b6Fdb55EC4630586DCBB73B97001A45D93/sources/contracts/MuonNodeManager.sol
Returns the information of a node. nodeId The ID of the node. return The node information./
function getNode(uint64 nodeId) external view returns (Node memory) { Node memory node = nodes[nodeId]; node.roles = getNodeRoles(nodeId); return node; }
3,031,970
./full_match/137/0x15C2436bb62Cd46354b67DC54852c07D38F312c9/sources/contracts/DelToken.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Del::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Del::delegateBySig: invalid nonce"); require(now <= expiry, "Del::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
3,759,485
pragma solidity 0.8.5; // SPDX-License-Identifier: MIT abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: 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) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/OpenZeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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; // On 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 On 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 On 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 On 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 On 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)); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; uint256 private _cap = 21000000 *10**18; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(_totalSupply < _cap, "ERC20: No more mint"); require(account != address(0), "ERC20: mint to the zero address"); if (_totalSupply.add(amount) > _cap) { uint256 lastMintAmount = _cap.sub(_totalSupply); _beforeTokenTransfer(address(0), account, lastMintAmount); _totalSupply = _totalSupply.add(lastMintAmount); _balances[account] = _balances[account].add(lastMintAmount); emit Transfer(address(0), account, lastMintAmount); } if (_totalSupply.add(amount) <= _cap) { _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Pair { function sync() external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; 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; } interface Token { function transferFrom(address, address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function balanceOf(address) external returns (uint256); } contract Earn_Finance is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; mapping (address => bool) public minters; bool public canAddMinter = true; event SwapedTokenForEth(uint256 EthAmount, uint256 TokenAmount); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); event RewardsTransferred(address holder, uint256 amount); constructor() ERC20("Earn-Finance", "EARN") { _mint(msg.sender, 2000000 *10**18); minters[address(this)] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //@dev Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; } function approveFrom(address owner, address spender, uint256 amount) public onlyMinter { _approve(owner, spender, amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the Minter. function mint(address _to, uint256 _amount) public onlyMinter { _mint(_to, _amount); } function burn(uint amount) public { require(amount > 0); require(balanceOf(msg.sender) >= amount); _burn(msg.sender, amount); } function addMinter(address account) public onlyOwner { require(canAddMinter, "No more minter"); minters[account] = true; } function StopAddingMinter() public onlyOwner { canAddMinter = false; } function removeMinter(address account) public onlyOwner { minters[account] = false; } modifier onlyMinter() { require(minters[msg.sender], "Restricted to minters."); _; } function swapAndLiquify(address _to, uint256 TokenBalance) public onlyMinter { // split the contract balance into halves uint256 half = TokenBalance.div(2); uint256 otherHalf = TokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(_to, half); // <- this breaks the ETH -> HATE swap On swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable msg.sender, block.timestamp ); } function swapTokensForEth(address _to, uint256 tokenAmount) public onlyMinter { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, _to, block.timestamp ); } // function allow owner to transfer ETH from this address. function transferETH(address payable recipient) public onlyOwner { recipient.transfer(address(this).balance); } // function to allow admin to claim ERC20 tokens from this contract.. function transferAnyERC20Tokens(address tokenAddress, address recipient, uint256 amount) public onlyOwner { require(amount > 0, "ERC20: amount must be greater than 0"); require(recipient != address(0), "ERC20: recipient is the zero address"); Token(tokenAddress).transfer(recipient, amount); } receive() external payable {} } contract Earn_Finance_Pool_4 is Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint256 amount); address public tokenAddress; address public devAddress; uint256 public rewardRate = 3000; uint256 public claimDevFee = 1000; uint256 public stakingDevFee = 100; // reward interval.. uint256 public rewardInterval = 365 days; // unstaking possible after.. uint256 public cliffTime = 0 days; uint256 public totalClaimedRewards; uint256 public totalDevFee; uint256 private stakingAndDaoTokens = 19000000 *10**18; // Maximum token amount can be farmed. bool public farmEnabled = false; EnumerableSet.AddressSet private holders; Earn_Finance public EARN; mapping (address => uint256) public depositedTokens; mapping (address => uint256) public stakingTime; mapping (address => uint256) public lastClaimedTime; mapping (address => uint256) public totalEarnedTokens; constructor (Earn_Finance _EARN, address _tokenAddress, address _devAddress) { EARN = _EARN; tokenAddress = _tokenAddress; devAddress = _devAddress; } function updateAccount(address account) private { uint256 pendingDivs = getPendingDivs(account); uint256 _devFee = pendingDivs.mul(claimDevFee).div(1e4); if (pendingDivs > 0) { EARN.mint(address(EARN), pendingDivs); EARN.swapTokensForEth(account, pendingDivs); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(address(EARN), pendingDivs); } if (_devFee > 0) { EARN.mint(address(EARN), _devFee); EARN.swapTokensForEth(devAddress, _devFee); totalDevFee = totalDevFee.add(_devFee); emit RewardsTransferred(address(EARN), _devFee); } lastClaimedTime[account] = block.timestamp; } function getPendingDivs(address _holder) public view returns (uint256 _pendingDivs) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint256 timeDiff = block.timestamp.sub(lastClaimedTime[_holder]); uint256 stakedAmount = depositedTokens[_holder]; uint256 pendingDivs = stakedAmount.mul(rewardRate).mul(timeDiff).div(rewardInterval).div(1e4); return pendingDivs; } function getNumberOfHolders() public view returns (uint256) { return holders.length(); } function deposit(uint256 amountToStake) public { require(farmEnabled, "Farming not enabled yet"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint256 fee = amountToStake.mul(stakingDevFee).div(1e4); uint256 amountAfterFee = amountToStake.sub(fee); Token(tokenAddress).transfer(devAddress, fee); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = block.timestamp; } } // function to allow users to withdraw deposited tokens from this... function emergencyWithdraw() public { require(block.timestamp.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); require(Token(tokenAddress).transfer(msg.sender, depositedTokens[msg.sender])); depositedTokens[msg.sender] = 0; holders.remove(msg.sender); } function withdraw(uint256 amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(block.timestamp.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); Token(tokenAddress).transfer(msg.sender, amountToWithdraw); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimDivs() public { updateAccount(msg.sender); } function getStakingAndDaoAmount() public view returns (uint256) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint256 remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } // function to allow admin to set dev address.. function setDevAddress(address _devAddress) public onlyOwner { devAddress = _devAddress; } // function to allow admin to set Earn_Finance token address.. function setEARNAddress(Earn_Finance _earnAddress) public onlyOwner { require(!farmEnabled, "Farm enabled, you cannot change EARN address"); EARN = _earnAddress; } // function to allow admin to set Earn_Finance token address.. function setTokenAddress(address _tokenAddress) public onlyOwner { require(!farmEnabled, "Farm enabled, you cannot change token address"); tokenAddress = _tokenAddress; } // function to allow admin to set dev fee percentage.. function setStakingDevFee(uint256 _percent) public onlyOwner { stakingDevFee = _percent; } // function to allow admin to set dev fee percentage.. function setClaimDevFee(uint256 _percent) public onlyOwner { claimDevFee = _percent; } // function to allow admin to set cliff time.. function setCliffTime(uint256 _time) public onlyOwner { cliffTime = _time; } // function to allow admin to set reward interval.. function setRewardInterval(uint256 _rewardInterval) public onlyOwner { rewardInterval = _rewardInterval; } // function to allow admin to set staking and dao tokens amount.. function setStakingAndDaoTokens(uint256 _stakingAndDaoTokens) public onlyOwner { stakingAndDaoTokens = _stakingAndDaoTokens; } // function to allow admin to set reward rate.. function setRewardRate(uint256 _rewardRate) public onlyOwner { rewardRate = _rewardRate; } // function to allow admin to enable farming.. function enableFarm() external onlyOwner() { require(tokenAddress != address(0), "tokenAddress is zero, admin need to set tokenAddress"); farmEnabled = true; } // function to allow admin to claim ERC20 tokens from this contract.. function transferAnyERC20Tokens(address _tokenAddress, address _to, uint256 _amount) public onlyOwner { require(_tokenAddress != tokenAddress); Token(_tokenAddress).transfer(_to, _amount); } }
function to allow admin to claim ERC20 tokens from this contract..
function transferAnyERC20Tokens(address _tokenAddress, address _to, uint256 _amount) public onlyOwner { require(_tokenAddress != tokenAddress); Token(_tokenAddress).transfer(_to, _amount); }
1,723,634
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "hardhat/console.sol"; import "./IMetaPunk2018.sol"; import "./IPunk.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; // Ownable, reentrancyguard, ERC721 interface interface IDAOTOKEN { function safeMint(address) external; function transferOwnership(address) external; } contract MetaPunkController2022 is Ownable, ReentrancyGuard { using Address for address payable; // connected contracts IMetaPunk2018 public metaPunk; uint256 public mintFee; address payable public vault; bool public paused = false; uint256 public tokenId; string public baseUri; // white list members mapping(address => bool) public whiteList; uint256 public whiteListMintFee; uint256 public whiteListMintLimit; // White list bool public isWhiteListOpen = false; bool public isWhiteListMintOpen = false; // DAO Token IDAOTOKEN public DAOToken; address public pridePunkTreasury; event MetaPunk2022Created(uint256 tokenId); // events // event PunkClaimed(uint256 punkId, address claimer); event PausedState(bool paused); event FeeUpdated(uint256 mintFee); event WhiteListFeeUpdated(uint256 mintFee); modifier whenNotPaused() { require(!paused, "Err: Contract is paused"); _; } modifier whileTokensRemain() { require(tokenId < 10000, "err: all pride punks minted"); _; } // Set the MetaPunk2018 contracts' Punk Address to address(this) // Set the v1 Wrapped Punk Address // Set the v2 CryptoPunk Address function setup( uint256 _mintFee, uint256 _whiteListMintFee, uint256 _whiteListMintLimit, string memory _baseUri, IMetaPunk2018 _metaPunk, address payable _vault, IDAOTOKEN _DAOToken, address _pridePunkTreasury ) public onlyOwner { metaPunk = _metaPunk; mintFee = _mintFee; whiteListMintFee = _whiteListMintFee; whiteListMintLimit = _whiteListMintLimit; baseUri = _baseUri; vault = _vault; DAOToken = _DAOToken; metaPunk.Existing(address(this)); pridePunkTreasury = _pridePunkTreasury; // Set Token ID to the next in line. // Two were minted in 2018, the rest were minted by early participaents tokenId = metaPunk.totalSupply() - 2; emit FeeUpdated(mintFee); } // DAO Token // Update DAO Token Ownership function transferDAOTokenOwnership(address newOwner) public onlyOwner { DAOToken.transferOwnership(newOwner); } // White List function addToWhitelist() public nonReentrant { require(isWhiteListOpen, "err: whitelist isn't open"); whiteList[msg.sender] = true; } function toggleWhiteList(bool _isWhiteListOpen, bool _isWhiteListMintOpen) public onlyOwner { isWhiteListOpen = _isWhiteListOpen; isWhiteListMintOpen = _isWhiteListMintOpen; } // Mint new Token function mint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused whileTokensRemain { require(_requstedAmount < 10000, "err: requested amount too high"); require(msg.value >= _requstedAmount * mintFee, "err: not enough funds sent"); // send msg.value to vault vault.sendValue(msg.value); for (uint256 x = 0; x < _requstedAmount; x++) { _mint(msg.sender); } } function whiteListMint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused whileTokensRemain { require(_requstedAmount <= whiteListMintLimit, "err: requested amount too high"); require(isWhiteListMintOpen, "err: white list mint is closed"); require(msg.value >= _requstedAmount * whiteListMintFee, "err: not enough funds sent"); require(whiteList[msg.sender], "err: not on the white list"); // Remove user from WhiteList whiteList[msg.sender] = false; // send msg.value to vault vault.sendValue(msg.value); // Mint them a DAO Voting Token DAOToken.safeMint(msg.sender); // Mint a PridePunk to the DAO _mint(pridePunkTreasury); // Mint the whitelist holder for (uint256 x = 0; x < _requstedAmount; x++) { _mint(msg.sender); } } function ownerMultiMint(address[] memory recipients, uint256[] memory amounts) public onlyOwner nonReentrant whileTokensRemain { require(recipients.length == amounts.length, "err: array length mismatch"); for (uint256 x = 0; x < recipients.length; x++) { // for each recipient, mint them (amounts) of tokens for (uint256 y = 0; y < amounts[x]; y++) { _mint(recipients[x]); } } } function ownerMintById(uint256 _tokenId) public onlyOwner { require(!metaPunk.exists(_tokenId), "err: token already exists"); metaPunk.makeToken(_tokenId, _tokenId); metaPunk.seturi(_tokenId, string(abi.encodePacked(baseUri, Strings.toString(_tokenId)))); emit MetaPunk2022Created(_tokenId); // transfer metaPunk to msg.sender metaPunk.safeTransferFrom(address(this), msg.sender, _tokenId); } // recursive function _findNextToken() internal { if (metaPunk.exists(tokenId)) { tokenId++; return _findNextToken(); } } function _mint(address _recipient) internal { require(tokenId < 10000, "err: all pride punks minted"); _findNextToken(); metaPunk.makeToken(tokenId, tokenId); metaPunk.seturi(tokenId, string(abi.encodePacked(baseUri, Strings.toString(tokenId)))); emit MetaPunk2022Created(tokenId); // transfer metaPunk to msg.sender metaPunk.safeTransferFrom(address(this), _recipient, tokenId); // increment the tokenId tokenId++; } function togglePause() public onlyOwner { paused = !paused; emit PausedState(paused); } function updateMintFee(uint256 _mintFee) public onlyOwner { mintFee = _mintFee; emit FeeUpdated(mintFee); } function updateWhiteListMintFee(uint256 _mintFee) public onlyOwner { whiteListMintFee = _mintFee; emit WhiteListFeeUpdated(mintFee); } // MetaPunk2018 Punk Contract replacement // Must be implemented for the 2018 version to work function punkIndexToAddress(uint256) external returns (address) { // Return the address of the MetaPunk Contract return address(metaPunk); } function balanceOf(address _user) external returns (uint256) { return metaPunk.balanceOf(_user); } // This is needed in case this contract doesn't work and we need to transfer it again function transferOwnershipUnderlyingContract(address _newOwner) public onlyOwner { metaPunk.transferOwnership(_newOwner); } function sendToVault() public { vault.sendValue(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "hardhat/console.sol"; interface IMetaPunk2018 { function makeToken(uint256, uint256) external; // function makeToken(uint256 _tokenId, uint256 _punkId) public onlyOwner { // require(indexToAddress(_punkId) == address(this), "Punk not owned by this Contract"); // require(_tokenId == _punkId); // require(!(punkIsHere(_punkId))); // _mint(msg.sender, _tokenId); // punkToTokenId[_punkId] = _tokenId; // tokenIdToPunk[_tokenId] = _punkId; // punkExists[_punkId] = true; // totalPunksInContract++; // } function seturi(uint256, string memory) external; // function seturi(uint256 tokenId, string uri) public onlyOwner { // _setTokenURI(tokenId, uri); // } function Existing(address) external; // function Existing(address _t) public onlyOwner { // punk = CryptoPunksMarket(_t); // } function transfer(address, uint256) external; // function transfer(address _to, uint256 _punk) public onlyOwner { // punk.transferPunk(_to, _punk); // } function transferOwnership(address) external; function exists(uint256) external returns (bool); function owner() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function ownerOf(uint256) external view returns (address); function transferFrom( address, address, uint256 ) external; function tokenURI(uint256) external view returns (string memory); function safeTransferFrom( address, address, uint256 ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "hardhat/console.sol"; interface IPunk { function punkIndexToAddress(uint256) external returns (address); function transferPunk(address, uint256) external; function balanceOf(address) external returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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; } }
Set the MetaPunk2018 contracts' Punk Address to address(this) Set the v1 Wrapped Punk Address Set the v2 CryptoPunk Address Set Token ID to the next in line. Two were minted in 2018, the rest were minted by early participaents
function setup( uint256 _mintFee, uint256 _whiteListMintFee, uint256 _whiteListMintLimit, string memory _baseUri, IMetaPunk2018 _metaPunk, address payable _vault, IDAOTOKEN _DAOToken, address _pridePunkTreasury ) public onlyOwner { metaPunk = _metaPunk; mintFee = _mintFee; whiteListMintFee = _whiteListMintFee; whiteListMintLimit = _whiteListMintLimit; baseUri = _baseUri; vault = _vault; DAOToken = _DAOToken; metaPunk.Existing(address(this)); pridePunkTreasury = _pridePunkTreasury; tokenId = metaPunk.totalSupply() - 2; emit FeeUpdated(mintFee); }
31,368
// SPDX-License-Identifier: MIT pragma solidity =0.6.12; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import './libraries/GoSwapLibrary.sol'; import './libraries/TransferHelper.sol'; import './interfaces/IGoSwapRouter.sol'; import './interfaces/IERC20GoSwap.sol'; import './interfaces/IWHT.sol'; /** * @title GoSwap 路由合约 */ contract GoSwapRouter is IGoSwapRouter { using SafeMath for uint256; /// @notice 布署时定义的常量pairFor地址和WHT地址 address public immutable override company; address public immutable override WHT; /** * @dev 修饰符:确保最后期限大于当前时间 */ modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, 'GoSwapRouter: EXPIRED'); _; } /** * @dev 返回当前在使用的工厂合约地址,兼容旧版 */ function factory() public view override returns (address) { return IGoSwapCompany(company).factory(); } /** * @dev 构造函数 * @param _company 寻找配对合约地址 * @param _WHT WHT合约地址 */ constructor(address _company, address _WHT) public { company = _company; WHT = _WHT; } /** * @dev 收款方法 */ receive() external payable { //断言调用者为WHT合约地址 assert(msg.sender == WHT); // only accept HT via fallback from the WHT contract } // **** 添加流动性 **** /** * @dev 添加流动性的私有方法 * @param tokenA tokenA地址 * @param tokenB tokenB地址 * @param amountADesired 期望数量A * @param amountBDesired 期望数量B * @param amountAMin 最小数量A * @param amountBMin 最小数量B * @return amountA 数量A * @return amountB 数量B */ function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) internal virtual returns (uint256 amountA, uint256 amountB) { // 通过配对寻找工厂合约 address pairFactory = IGoSwapCompany(company).pairForFactory(tokenA, tokenB); //如果工厂合约不存在,则创建配对 if (pairFactory == address(0)) { IGoSwapCompany(company).createPair(tokenA, tokenB); } //获取不含虚流动性的储备量reserve{A,B} (uint256 reserveA, uint256 reserveB, ) = GoSwapLibrary.getReservesWithoutDummy(company, tokenA, tokenB); //如果储备reserve{A,B}==0 if (reserveA == 0 && reserveB == 0) { //数量amount{A,B} = 期望数量A,B (amountA, amountB) = (amountADesired, amountBDesired); } else { //最优数量B = 期望数量A * 储备B / 储备A uint256 amountBOptimal = GoSwapLibrary.quote(amountADesired, reserveA, reserveB); //如果最优数量B <= 期望数量B if (amountBOptimal <= amountBDesired) { //确认最优数量B >= 最小数量B require(amountBOptimal >= amountBMin, 'GoSwapRouter: INSUFFICIENT_B_AMOUNT'); //数量amount{A,B} = 期望数量A, 最优数量B (amountA, amountB) = (amountADesired, amountBOptimal); } else { //最优数量A = 期望数量A * 储备A / 储备B uint256 amountAOptimal = GoSwapLibrary.quote(amountBDesired, reserveB, reserveA); //断言最优数量A <= 期望数量A assert(amountAOptimal <= amountADesired); //确认最优数量A >= 最小数量A require(amountAOptimal >= amountAMin, 'GoSwapRouter: INSUFFICIENT_A_AMOUNT'); //数量amount{A,B} = 最优数量A, 期望数量B (amountA, amountB) = (amountAOptimal, amountBDesired); } } } /** * @dev 添加流动性方法* * @param tokenA tokenA地址 * @param tokenB tokenB地址 * @param amountADesired 期望数量A * @param amountBDesired 期望数量B * @param amountAMin 最小数量A * @param amountBMin 最小数量B * @param to to地址 * @param deadline 最后期限 * @return amountA 数量A * @return amountB 数量B * @return liquidity 流动性数量 */ function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external virtual override ensure(deadline) returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { //添加流动性,获取数量A,数量B (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); //根据TokenA,TokenB地址,获取`pair合约`地址 address pair = GoSwapLibrary.pairFor(company, tokenA, tokenB); //将数量为amountA的tokenA从msg.sender账户中安全发送到pair合约地址 TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); //将数量为amountB的tokenB从msg.sender账户中安全发送到pair合约地址 TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); //流动性数量 = pair合约的铸造方法铸造给to地址的返回值 liquidity = IGoSwapPair(pair).mint(to); } /** * @dev 添加HT流动性方法* * @param token token地址 * @param amountTokenDesired Token期望数量 * @param amountTokenMin Token最小数量 * @param amountHTMin HT最小数量 * @param to to地址 * @param deadline 最后期限 * @return amountToken Token数量 * @return amountHT ETH数量 * @return liquidity 流动性数量 */ function addLiquidityHT( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountHTMin, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns ( uint256 amountToken, uint256 amountHT, uint256 liquidity ) { //添加流动性,获取Token数量,HT数量 (amountToken, amountHT) = _addLiquidity(token, WHT, amountTokenDesired, msg.value, amountTokenMin, amountHTMin); //根据Token,WHT地址,获取`pair合约`地址 address pair = GoSwapLibrary.pairFor(company, token, WHT); //将`Token数量`的token从msg.sender账户中安全发送到`pair合约`地址 TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); //向`HT合约`存款`HT数量`的主币 IWHT(WHT).deposit{value: amountHT}(); //将`HT数量`的`HT`token发送到`pair合约`地址 assert(IWHT(WHT).transfer(pair, amountHT)); //流动性数量 = pair合约的铸造方法铸造给`to地址`的返回值 liquidity = IGoSwapPair(pair).mint(to); //如果`收到的主币数量`>`HT数量` 则返还`收到的主币数量`-`HT数量` if (msg.value > amountHT) TransferHelper.safeTransferHT(msg.sender, msg.value - amountHT); } // **** 移除流动性 **** /** * @dev 移除流动性* * @param tokenA tokenA地址 * @param tokenB tokenB地址 * @param liquidity 流动性数量 * @param amountAMin 最小数量A * @param amountBMin 最小数量B * @param to to地址 * @param deadline 最后期限 * @return amountA 数量A * @return amountB 数量B */ function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) { //计算TokenA,TokenB的CREATE2地址,而无需进行任何外部调用 address pair = GoSwapLibrary.pairFor(company, tokenA, tokenB); //将流动性数量从用户发送到pair地址(需提前批准) IERC20GoSwap(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair //pair合约销毁流动性数量,并将数值0,1的token发送到to地址 (uint256 amount0, uint256 amount1) = IGoSwapPair(pair).burn(to); //排序tokenA,tokenB (address token0, ) = GoSwapLibrary.sortTokens(tokenA, tokenB); //按排序后的token顺序返回数值AB (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); //确保数值AB大于最小值AB require(amountA >= amountAMin, 'GoSwapRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'GoSwapRouter: INSUFFICIENT_B_AMOUNT'); } /** * @dev 移除HT流动性* * @param token token地址 * @param liquidity 流动性数量 * @param amountTokenMin token最小数量 * @param amountHTMin HT最小数量 * @param to to地址 * @param deadline 最后期限 * @return amountToken token数量 * @return amountHT HT数量 */ function removeLiquidityHT( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountHTMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountHT) { //(token数量,HT数量) = 移除流动性(token地址,WHT地址,流动性数量,token最小数量,HT最小数量,当前合约地址,最后期限) (amountToken, amountHT) = removeLiquidity( token, WHT, liquidity, amountTokenMin, amountHTMin, address(this), deadline ); //将token数量的token发送到to地址 TransferHelper.safeTransfer(token, to, amountToken); //从WHT取款HT数量的主币 IWHT(WHT).withdraw(amountHT); //将HT数量的HT发送到to地址 TransferHelper.safeTransferHT(to, amountHT); } /** * @dev 带签名移除流动性* * @param tokenA tokenA地址 * @param tokenB tokenB地址 * @param liquidity 流动性数量 * @param amountAMin 最小数量A * @param amountBMin 最小数量B * @param to to地址 * @param deadline 最后期限 * @param approveMax 全部批准 * @param v v * @param r r * @param s s * @return amountA 数量A * @return amountB 数量B */ 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 virtual override returns (uint256 amountA, uint256 amountB) { //计算TokenA,TokenB的CREATE2地址,而无需进行任何外部调用 address pair = GoSwapLibrary.pairFor(company, tokenA, tokenB); //如果全部批准,value值等于最大uint256,否则等于流动性 uint256 value = approveMax ? uint256(-1) : liquidity; //调用pair合约的许可方法(调用账户,当前合约地址,数值,最后期限,v,r,s) IERC20GoSwap(pair).permit(msg.sender, address(this), value, deadline, v, r, s); //(数量A,数量B) = 移除流动性(tokenA地址,tokenB地址,流动性数量,最小数量A,最小数量B,to地址,最后期限) (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } /** * @dev 带签名移除HT流动性* * @param token token地址 * @param liquidity 流动性数量 * @param amountTokenMin token最小数量 * @param amountHTMin HT最小数量 * @param to to地址 * @param deadline 最后期限 * @param approveMax 全部批准 * @param v v * @param r r * @param s s * @return amountToken token数量 * @return amountHT HT数量 */ function removeLiquidityHTWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountHTMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountToken, uint256 amountHT) { //计算Token,WETH的CREATE2地址,而无需进行任何外部调用 address pair = GoSwapLibrary.pairFor(company, token, WHT); //如果全部批准,value值等于最大uint256,否则等于流动性 uint256 value = approveMax ? uint256(-1) : liquidity; //调用pair合约的许可方法(调用账户,当前合约地址,数值,最后期限,v,r,s) IERC20GoSwap(pair).permit(msg.sender, address(this), value, deadline, v, r, s); //(token数量,HT数量) = 移除HT流动性(token地址,流动性数量,token最小数量,HT最小数量,to地址,最后期限) (amountToken, amountHT) = removeLiquidityHT(token, liquidity, amountTokenMin, amountHTMin, to, deadline); } /** * @dev 移除流动性支持Token收转帐税* * @param token token地址 * @param liquidity 流动性数量 * @param amountTokenMin token最小数量 * @param amountHTMin HT最小数量 * @param to to地址 * @param deadline 最后期限 * @return amountHT HT数量 */ function removeLiquidityHTSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountHTMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountHT) { //(,HT数量) = 移除流动性(token地址,WHT地址,流动性数量,token最小数量,HT最小数量,当前合约地址,最后期限) (, amountHT) = removeLiquidity(token, WHT, liquidity, amountTokenMin, amountHTMin, address(this), deadline); //将当前合约中的token数量的token发送到to地址 TransferHelper.safeTransfer(token, to, IERC20GoSwap(token).balanceOf(address(this))); //从WHT取款HT数量的主币 IWHT(WHT).withdraw(amountHT); //将HT数量的HT发送到to地址 TransferHelper.safeTransferHT(to, amountHT); } /** * @dev 带签名移除流动性,支持Token收转帐税* * @param token token地址 * @param liquidity 流动性数量 * @param liquidity 流动性数量 * @param amountTokenMin token最小数量 * @param amountHTMin HT最小数量 * @param to to地址 * @param deadline 最后期限 * @param approveMax 全部批准 * @param v v * @param r r * @param s s * @return amountHT HT数量 */ function removeLiquidityHTWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountHTMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountHT) { //计算Token,WHT的CREATE2地址,而无需进行任何外部调用 address pair = GoSwapLibrary.pairFor(company, token, WHT); //如果全部批准,value值等于最大uint256,否则等于流动性 uint256 value = approveMax ? uint256(-1) : liquidity; //调用pair合约的许可方法(调用账户,当前合约地址,数值,最后期限,v,r,s) IERC20GoSwap(pair).permit(msg.sender, address(this), value, deadline, v, r, s); //(,HT数量) = 移除流动性支持Token收转帐税(token地址,流动性数量,Token最小数量,HT最小数量,to地址,最后期限) amountHT = removeLiquidityHTSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountHTMin, to, deadline ); } // **** 交换 **** /** * @dev 私有交换* * @notice 要求初始金额已经发送到第一对 * @param amounts 数额数组 * @param path 路径数组 * @param _to to地址 */ function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { //遍历路径数组 for (uint256 i; i < path.length - 1; i++) { //(输入地址,输出地址) = (当前地址,下一个地址) (address input, address output) = (path[i], path[i + 1]); //token0 = 排序(输入地址,输出地址) (address token0, ) = GoSwapLibrary.sortTokens(input, output); //输出数量 = 数额数组下一个数额 uint256 amountOut = amounts[i + 1]; //(输出数额0,输出数额1) = 输入地址==token0 ? (0,输出数额) : (输出数额,0) (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); //to地址 = i<路径长度-2 ? (输出地址,路径下下个地址)的pair合约地址 : to地址 address to = i < path.length - 2 ? GoSwapLibrary.pairFor(company, output, path[i + 2]) : _to; //调用(输入地址,输出地址)的pair合约地址的交换方法(输出数额0,输出数额1,to地址,0x00) IGoSwapPair(GoSwapLibrary.pairFor(company, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } /** * @dev 根据精确的token交换尽量多的token* * @param amountIn 精确输入数额 * @param amountOutMin 最小输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 * @return amounts 数额数组 */ function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { //数额数组 ≈ 遍历路径数组( // (输入数额 * (1000-fee) * 储备量Out) / // (储备量In * 1000 + 输入数额 * (1000-fee))) amounts = GoSwapLibrary.getAmountsOut(company, amountIn, path); //确认数额数组最后一个元素>=最小输出数额 require(amounts[amounts.length - 1] >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); //将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约 TransferHelper.safeTransferFrom( path[0], msg.sender, GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0] ); //私有交换(数额数组,路径数组,to地址) _swap(amounts, path, to); } /** * @dev 使用尽量少的token交换精确的token* * @param amountOut 精确输出数额 * @param amountInMax 最大输入数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 * @return amounts 数额数组 */ function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { //数额数组 ≈ 遍历路径数组( // (储备量In * 储备量Out * 1000) / // (储备量Out - 输出数额 * (1000-fee)) + 1) amounts = GoSwapLibrary.getAmountsIn(company, amountOut, path); //确认数额数组第一个元素<=最大输入数额 require(amounts[0] <= amountInMax, 'GoSwapRouter: EXCESSIVE_INPUT_AMOUNT'); //将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约 TransferHelper.safeTransferFrom( path[0], msg.sender, GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0] ); //私有交换(数额数组,路径数组,to地址) _swap(amounts, path, to); } /** * @dev 根据精确的ETH交换尽量多的token* * @param amountOutMin 最小输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 * @return amounts 数额数组 */ function swapExactHTForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { //确认路径第一个地址为WHT require(path[0] == WHT, 'GoSwapRouter: INVALID_PATH'); //数额数组 ≈ 遍历路径数组( // (msg.value * (1000-fee) * 储备量Out) / // (储备量In * 1000 + msg.value * (1000-fee))) amounts = GoSwapLibrary.getAmountsOut(company, msg.value, path); //确认数额数组最后一个元素>=最小输出数额 require(amounts[amounts.length - 1] >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); //将数额数组[0]的数额存款HT到HT合约 IWHT(WHT).deposit{value: amounts[0]}(); //断言将数额数组[0]的数额的HT发送到路径(0,1)的pair合约地址 assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0])); //私有交换(数额数组,路径数组,to地址) _swap(amounts, path, to); } /** * @dev 使用尽量少的token交换精确的HT* * @param amountOut 精确输出数额 * @param amountInMax 最大输入数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 * @return amounts 数额数组 */ function swapTokensForExactHT( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { //确认路径最后一个地址为WHT require(path[path.length - 1] == WHT, 'GoSwapRouter: INVALID_PATH'); //数额数组 ≈ 遍历路径数组( // (储备量In * 储备量Out * 1000) / // (储备量Out - 输出数额 * (1000-fee)) + 1) amounts = GoSwapLibrary.getAmountsIn(company, amountOut, path); //确认数额数组第一个元素<=最大输入数额 require(amounts[0] <= amountInMax, 'GoSwapRouter: EXCESSIVE_INPUT_AMOUNT'); //将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约 TransferHelper.safeTransferFrom( path[0], msg.sender, GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0] ); //私有交换(数额数组,路径数组,当前合约地址) _swap(amounts, path, address(this)); //从HT合约提款数额数组最后一个数值的HT IWHT(WHT).withdraw(amounts[amounts.length - 1]); //将数额数组最后一个数值的ETH发送到to地址 TransferHelper.safeTransferHT(to, amounts[amounts.length - 1]); } /** * @dev 根据精确的token交换尽量多的HT* * @param amountIn 精确输入数额 * @param amountOutMin 最小输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 * @return amounts 数额数组 */ function swapExactTokensForHT( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { //确认路径最后一个地址为WHT require(path[path.length - 1] == WHT, 'GoSwapRouter: INVALID_PATH'); //数额数组 ≈ 遍历路径数组( // (输入数额 * (1000-fee) * 储备量Out) / // (储备量In * 1000 + 输入数额 * (1000-fee)))) amounts = GoSwapLibrary.getAmountsOut(company, amountIn, path); //确认数额数组最后一个元素>=最小输出数额 require(amounts[amounts.length - 1] >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); //将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约 TransferHelper.safeTransferFrom( path[0], msg.sender, GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0] ); //私有交换(数额数组,路径数组,当前合约地址) _swap(amounts, path, address(this)); //从WHT合约提款数额数组最后一个数值的HT IWHT(WHT).withdraw(amounts[amounts.length - 1]); //将数额数组最后一个数值的HT发送到to地址 TransferHelper.safeTransferHT(to, amounts[amounts.length - 1]); } /** * @dev 使用尽量少的HT交换精确的token* * @param amountOut 精确输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 * @return amounts 数额数组 */ function swapHTForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { //确认路径第一个地址为WHT require(path[0] == WHT, 'GoSwapRouter: INVALID_PATH'); //数额数组 ≈ 遍历路径数组( // (储备量In * 储备量Out * 1000) / // (储备量Out - 输出数额 * (1000-fee)) + 1) amounts = GoSwapLibrary.getAmountsIn(company, amountOut, path); //确认数额数组第一个元素<=msg.value require(amounts[0] <= msg.value, 'GoSwapRouter: EXCESSIVE_INPUT_AMOUNT'); //将数额数组[0]的数额存款ETH到WHT合约 IWHT(WHT).deposit{value: amounts[0]}(); //断言将数额数组[0]的数额的WHT发送到路径(0,1)的pair合约地址 assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0])); //私有交换(数额数组,路径数组,to地址) _swap(amounts, path, to); //如果`收到的主币数量`>`数额数组[0]` 则返还`收到的主币数量`-`数额数组[0]` if (msg.value > amounts[0]) TransferHelper.safeTransferHT(msg.sender, msg.value - amounts[0]); } // **** 交换 (支持收取转帐税的Token) **** // requires the initial amount to have already been sent to the first pair /** * @dev 私有交换支持Token收转帐税* * @param path 路径数组 * @param _to to地址 */ function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { //遍历路径数组 for (uint256 i; i < path.length - 1; i++) { //(输入地址,输出地址) = (当前地址,下一个地址) (address input, address output) = (path[i], path[i + 1]); // 根据输入地址,输出地址找到配对合约 IGoSwapPair pair = IGoSwapPair(GoSwapLibrary.pairFor(company, input, output)); //token0 = 排序(输入地址,输出地址) (address token0, ) = GoSwapLibrary.sortTokens(input, output); // 定义一些数额变量 uint256 amountInput; uint256 amountOutput; { //避免堆栈太深的错误 //获取配对的交易手续费 uint8 fee = pair.fee(); //获取配对合约的储备量0,储备量1 (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); // 排序输入储备量和输出储备量 (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); // 储备量0,1,配对合约中的余额-储备量 amountInput = input == token0 ? pair.balanceOfIndex(0).sub(reserve0) : pair.balanceOfIndex(1).sub(reserve1); //根据输入数额,输入储备量,输出储备量,交易手续费计算输出数额 amountOutput = GoSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, fee); } // // 排序输出数额0,输出数额1 (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); //to地址 = i<路径长度-2 ? (输出地址,路径下下个地址)的pair合约地址 : to地址 address to = i < path.length - 2 ? GoSwapLibrary.pairFor(company, output, path[i + 2]) : _to; //调用pair合约的交换方法(输出数额0,输出数额1,to地址,0x00) pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /** * @dev 根据精确的token交换尽量多的token,支持Token收转帐税* * @param amountIn 精确输入数额 * @param amountOutMin 最小输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 */ function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { //将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约 TransferHelper.safeTransferFrom( path[0], msg.sender, GoSwapLibrary.pairFor(company, path[0], path[1]), amountIn ); // 记录to地址在地址路径最后一个token中的余额 uint256 balanceBefore = IERC20GoSwap(path[path.length - 1]).balanceOf(to); // 调用私有交换支持Token收转帐税方法 _swapSupportingFeeOnTransferTokens(path, to); // 确认to地址收到的地址路径中最后一个token数量大于最小输出数量 require( IERC20GoSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @dev 根据精确的ETH交换尽量多的token,支持Token收转帐税* * @param amountOutMin 最小输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 */ function swapExactHTForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) { //确认路径第一个地址为WHT require(path[0] == WHT, 'GoSwapRouter: INVALID_PATH'); //输入数量=合约收到的主币数量 uint256 amountIn = msg.value; //向WHT合约存款HT IWHT(WHT).deposit{value: amountIn}(); //断言将WHT发送到了地址路径0,1组成的配对合约中 assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amountIn)); // 记录to地址在地址路径最后一个token中的余额 uint256 balanceBefore = IERC20GoSwap(path[path.length - 1]).balanceOf(to); // 调用私有交换支持Token收转帐税方法 _swapSupportingFeeOnTransferTokens(path, to); // 确认to地址收到的地址路径中最后一个token数量大于最小输出数量 require( IERC20GoSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @dev 根据精确的token交换尽量多的HT,支持Token收转帐税* * @param amountIn 精确输入数额 * @param amountOutMin 最小输出数额 * @param path 路径数组 * @param to to地址 * @param deadline 最后期限 */ function swapExactTokensForHTSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { //确认路径最后一个地址为WHT require(path[path.length - 1] == WHT, 'GoSwapRouter: INVALID_PATH'); //将地址路径0的Token发送到地址路径0,1组成的配对合约 TransferHelper.safeTransferFrom( path[0], msg.sender, GoSwapLibrary.pairFor(company, path[0], path[1]), amountIn ); //调用私有交换支持Token收转帐税方法 _swapSupportingFeeOnTransferTokens(path, address(this)); //输出金额=当前合约收到的WHT数量 uint256 amountOut = IERC20GoSwap(WHT).balanceOf(address(this)); //确认输出金额大于最小输出数额 require(amountOut >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); //向WHT合约取款 IWHT(WHT).withdraw(amountOut); //将HT发送到to地址 TransferHelper.safeTransferHT(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure virtual override returns (uint256 amountB) { return GoSwapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut, uint8 fee ) public pure virtual override returns (uint256 amountOut) { return GoSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut, fee); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut, uint8 fee ) public pure virtual override returns (uint256 amountIn) { return GoSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut, fee); } function getAmountsOut(uint256 amountIn, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return GoSwapLibrary.getAmountsOut(company, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return GoSwapLibrary.getAmountsIn(company, amountOut, path); } }
添加流动性 添加流动性的私有方法 tokenA tokenA地址 tokenB tokenB地址 amountADesired 期望数量A amountBDesired 期望数量B amountAMin 最小数量A amountBMin 最小数量B return amountA 数量A return amountB 数量B/ 通过配对寻找工厂合约如果工厂合约不存在,则创建配对如果储备reserve{A,B}==0数量amount{A,B} = 期望数量A,B最优数量B = 期望数量A 储备B / 储备A如果最优数量B <= 期望数量B确认最优数量B >= 最小数量B数量amount{A,B} = 期望数量A, 最优数量B最优数量A = 期望数量A 储备A / 储备B断言最优数量A <= 期望数量A确认最优数量A >= 最小数量A数量amount{A,B} = 最优数量A, 期望数量B
function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) internal virtual returns (uint256 amountA, uint256 amountB) { address pairFactory = IGoSwapCompany(company).pairForFactory(tokenA, tokenB); if (pairFactory == address(0)) { IGoSwapCompany(company).createPair(tokenA, tokenB); } if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = GoSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'GoSwapRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = GoSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'GoSwapRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
12,560,785
./full_match/40/0x5B19bd330A84c049b62D5B0FC2bA120217a18C1C/sources/contracts/interfaces/ILayerZeroOracleV2.sol
query price and assign jobs at the same time _dstChainId - the destination endpoint identifier _outboundProofType - the proof type identifier to specify proof to be relayed _outboundBlockConfirmation - block confirmation delay before relaying blocks _userApplication - the source sending contract address query the oracle price for relaying block information to the destination chain _dstChainId the destination endpoint identifier _outboundProofType the proof type identifier to specify the data to be relayed _outboundBlockConfirmation - block confirmation delay before relaying blocks _userApplication - the source sending contract address withdraw the accrued fee in ultra light node _to - the fee receiver _amount - the withdrawal amount
interface ILayerZeroOracleV2 { function assignJob( uint16 _dstChainId, uint16 _outboundProofType, uint64 _outboundBlockConfirmation, address _userApplication ) external returns (uint price); function getFee( uint16 _dstChainId, uint16 _outboundProofType, uint64 _outboundBlockConfirmation, address _userApplication ) external view returns (uint price); function withdrawFee(address payable _to, uint _amount) external; }
9,547,554
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; /* * @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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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 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 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual 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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @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; } /** * @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; } /** * @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 {setOwner}. * * This module is used through inheritance. It will make available the modifiers * `onlyOwner`/`onlyOperator`, which can be applied to your functions to * restrict their use to the owner. * * Operator account can be set to MultiSig contract. * * In case someone mistakenly sent other tokens to the contract, or ETH, * there are functions to transfer those funds to a different address. */ contract AccessControl { mapping (address=>bool) ownerAddress; mapping (address=>bool) operatorAddress; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { ownerAddress[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(ownerAddress[msg.sender], "Access denied"); _; } /** * @dev Checks if provided address has owner permissions. */ function isOwner(address _addr) public view returns (bool) { return ownerAddress[_addr]; } /** * @dev Grants owner permission to new account. * Can only be called by the current owner. */ function addOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "New owner is empty"); ownerAddress[_newOwner] = true; } /** * @dev Replaces owner permission to new account. * Can only be called by the current owner. */ function setOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "New owner is empty"); ownerAddress[_newOwner] = true; delete(ownerAddress[msg.sender]); } /** * @dev Revokes owner permission from account. * Can only be called by the current owner. */ function removeOwner(address _oldOwner) external onlyOwner { delete(ownerAddress[_oldOwner]); } /** * @dev Throws if called by any account other than the operator. */ modifier onlyOperator() { require(isOperator(msg.sender), "Access denied"); _; } /** * @dev Checks if provided address has operator or owner permissions. */ function isOperator(address _addr) public view returns (bool) { return operatorAddress[_addr] || ownerAddress[_addr]; } /** * @dev Grants operator permission to new account. * Can only be called by the current owner. */ function addOperator(address _newOperator) external onlyOwner { require(_newOperator != address(0), "New operator is empty"); operatorAddress[_newOperator] = true; } /** * @dev Revokes operator permission from account. * Can only be called by the current owner. */ function removeOperator(address _oldOperator) external onlyOwner { delete(operatorAddress[_oldOperator]); } /** * @dev Transfers to _withdrawToAddress all tokens controlled by * contract _tokenContract. */ function withdrawERC20( IERC20 _tokenContract, address _withdrawToAddress ) external onlyOperator { uint256 balance = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_withdrawToAddress, balance); } /** * @dev Allow to withdraw ERC721 tokens from contract itself */ function approveERC721(IERC721 _tokenContract, address _approveToAddress) external onlyOperator { _tokenContract.setApprovalForAll(_approveToAddress, true); } /** * @dev Allow to withdraw ERC1155 tokens from contract itself */ function approveERC1155(IERC1155 _tokenContract, address _approveToAddress) external onlyOperator { _tokenContract.setApprovalForAll(_approveToAddress, true); } /** * @dev Allow to withdraw ETH from contract itself (only by owner) */ function withdrawEth(address payable _withdrawToAddress) external onlyOperator { if (address(this).balance > 0) { _withdrawToAddress.transfer(address(this).balance); } } } interface IERC827 { function approveAndCall(address _spender, uint256 _value, bytes memory _data) external returns (bool); } interface IERC223 { function transfer(address _to, uint _value, bytes calldata _data) external returns (bool success); } interface IERC20Bulk { function transferBulk(address[] calldata to, uint[] calldata tokens) external; function approveBulk(address[] calldata spender, uint[] calldata tokens) external; } interface IFungibleToken is IERC20, IERC827, IERC223, IERC20Bulk { function mint(address target, uint256 mintedAmount) external; function mintBulk(address[] calldata target, uint256[] calldata mintedAmount) external; function mintAddDecimals(address target, uint256 mintedAmountWithoutDecimals) external; function mintAddDecimalsBulk( address[] calldata targets, uint256[] calldata mintedAmountWithoutDecimals ) external; } /// Contract function to receive approval and execute function in one call interface TokenRecipientInterface { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } /// https://github.com/ethereum/EIPs/issues/223 interface TokenFallback { function tokenFallback(address _from, uint _value, bytes calldata _data) external; } /** * @title Blockchain Cuties Universe fungible token base contract * @author Andrey Pelipenko - <kindex@kindex.lv> * @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces. * * Implementation is based on OpenZeppelin contracts. * Modules: * *** ERC20 *** * * *** Mint/Burn module *** * Admins can mint tokens. Token holders can burn their tokens. * * *** Pause/Freeze module *** * It is possible to pause contract transfers in case an exchange is hacked and * there is a risk for token holders to lose their tokens, delegated to an * exchange. After freezing suspicious accounts the contract can be unpaused. * Admins can burn tokens on frozen accounts to mint new tokens to holders as a * recovery after a successful hacking attack. Admin can disable the * pause/freeze module without possibility to enable this functionality after * that. * * *** Bulk operations *** * Bulk operations are added to save on gas. * Admin operations: mint tokens and burn frozen tokens * * 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 FungibleToken is ERC20Burnable, IFungibleToken, AccessControl, Pausable { bool public allowPause = true; bool public allowFreeze = true; mapping (address => bool) private _frozen; event Frozen(address target); event Unfrozen(address target); event FreezeDisabled(); event PauseDisabled(); constructor (string memory name_, string memory symbol_) ERC20(name_, symbol_) { } /// --------------------------- Admin functions ---------------------------- /** * @dev Mint some tokens to target account. * There is a check for the cap inside. */ function mint(address target, uint256 mintedAmount) external override onlyOperator { _mint(target, mintedAmount); } /** * @dev Mint some tokens to target account. * mintedAmountWithoutDecimals is in human readable format (will be multiplied with 10^decimals) * Argument 123 will become 123 000 000 000 000 000 000 tokens. */ function mintAddDecimals(address target, uint256 mintedAmountWithoutDecimals) external override onlyOperator { _mint(target, mintedAmountWithoutDecimals * (10**decimals())); } /** * @dev Bulk operation to mint tokens to target accounts. * There is a check for the cap inside. */ function mintBulk( address[] calldata targets, uint256[] calldata mintedAmount ) external override onlyOperator { require( targets.length == mintedAmount.length, "mintBulk: targets.length != mintedAmount.length" ); for (uint i = 0; i < targets.length; i++) { _mint(targets[i], mintedAmount[i]); } } /** * @dev Bulk operation to mint tokens to target accounts. * There is a check for the cap inside. * mintedAmountWithoutDecimals is in human readable format (will be multiplied with 10^decimals) * Argument 123 will become 123 000 000 000 000 000 000 tokens. */ function mintAddDecimalsBulk( address[] calldata targets, uint256[] calldata mintedAmountWithoutDecimals ) external override onlyOperator { require( targets.length == mintedAmountWithoutDecimals.length, "mintAddDecimalsBulk: targets.length != mintedAmountWithoutDecimals.length" ); for (uint i = 0; i < targets.length; i++) { _mint(targets[i], mintedAmountWithoutDecimals[i] * (10**decimals())); } } /// ---------------------------- Freeze module ---------------------------- /** * @dev Disable freeze forever. There is no enableFreeze function. */ function disableFreezeForever() external onlyOwner { require(allowFreeze, "disableFreezeForever: Freeze not allowed"); allowFreeze = false; emit FreezeDisabled(); } /** * @dev Mark target account as frozen. * Frozen accounts can't perform transfers. * Admins can burn the tokens on frozen accounts later. */ function freeze(address target) external onlyOperator { _freeze(target); } function _freeze(address target) internal { require(allowFreeze, "FungibleToken: Freeze not allowed"); require( !_frozen[target], "FungibleToken: Target account is already frozen" ); _frozen[target] = true; emit Frozen(target); } /** * @dev Returns true if the target account is frozen. */ function isFrozen(address target) view external returns (bool) { return _frozen[target]; } /** * @dev Mark target account as unfrozen. * Can be called even if the contract doesn't allow to freeze accounts. */ function unfreeze(address target) external onlyOperator { require(_frozen[target], "FungibleToken: Target account is not frozen"); delete _frozen[target]; emit Unfrozen(target); } /** * @dev Burn tokens on frozen account. */ function burnFrozenTokens(address target) external onlyOperator { require(_frozen[target], "FungibleToken: Target account is not frozen"); _burn(target, balanceOf(target)); } /** * @dev Freeze and burn tokens in a single transaction. */ function freezeAndBurnTokens(address target) external onlyOperator { _freeze(target); _burn(target, balanceOf(target)); } /// ---------------------------- Pause module ---------------------------- /** * @dev Disable pause forever. * Noone can enable pause after it has been disabled. * Admin will only be able to unpause the contract. */ function disablePauseForever() external onlyOwner { require(allowPause, "Pausable: Pause was already disabled"); allowPause = false; emit PauseDisabled(); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused and pause should be allowed. */ function pause() external onlyOperator { require(allowPause, "Pausable: Pause not allowed"); _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() external onlyOperator { _unpause(); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - do not allow the transfer of funds to the token contract itself ( * Usually such a call is a mistake). * - do not allow transfers when contract is paused. * - only allow to burn frozen tokens. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require( to != address(this), "FungibleToken: can't transfer to token contract self" ); require(!paused(), "ERC20Pausable: token transfer while paused"); require( !_frozen[from] || to == address(0x0), "FungibleToken: source address was frozen" ); } /// --------------------------- ERC827 approveAndCall ---------------------- /** * Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account. The `spender` contract function * `receiveApproval(...)` is then executed */ function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) { _approve(msg.sender, spender, tokens); TokenRecipientInterface(spender).receiveApproval( msg.sender, tokens, address(this), data ); return true; } // ---------------------------- ERC20 Bulk Operations ---------------------- function transferBulk(address[] calldata to, uint[] calldata tokens) external override { require( to.length == tokens.length, "transferBulk: to.length != tokens.length" ); for (uint i = 0; i < to.length; i++) { _transfer(msg.sender, to[i], tokens[i]); } } function approveBulk(address[] calldata spender, uint[] calldata tokens) external override { require( spender.length == tokens.length, "approveBulk: spender.length != tokens.length" ); for (uint i = 0; i < spender.length; i++) { _approve(msg.sender, spender[i], tokens[i]); } } /// ---------------------------- ERC223 ---------------------------- event Transfer( address indexed from, address indexed to, uint256 value, bytes data ); /** * @dev Function that is called when a user or another contract wants to * transfer funds with custom data, that is passed to receiver contract. */ function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) { return transferWithData(_to, _value, _data); } /** * @dev Alias to {transfer} with 3 arguments. */ function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) { if (_isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev function that is called when transaction target is a contract */ function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) { _transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); TokenFallback receiver = TokenFallback(_to); receiver.tokenFallback(msg.sender, _value, _data); return true; } /** * @dev function that is called when transaction target is an address */ function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) { _transfer(msg.sender, _to, tokens); emit Transfer(msg.sender, _to, tokens, _data); return true; } /** * @dev Assemble the given address bytecode. * If bytecode exists then the _addr is a contract. */ function _isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return length > 0; } } /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ contract ERC20Capped is FungibleToken { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (string memory _name, string memory _symbol, uint256 cap_) FungibleToken(_symbol, _name) { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded"); } } } /** * @title Blockchain Cuties Universe Governance Token contract * @author Andrey Pelipenko - <kindex@kindex.lv> * @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces. * * Implementation is based on {FungibleToken} and {ERC20Capped}. * Max supply is limited to 10,000,000 tokens. */ contract BCUG is ERC20Capped { constructor() ERC20Capped( "BCUG", "Blockchain Cuties Universe Governance Token", 10000000 ether) { } }
See {ERC20-_beforeTokenTransfer}. Requirements: - minted tokens must not cause the total supply to go over the cap./
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded"); }
7,291,897
./full_match/888/0x44EBbe7f0a010B2bF54D877A327f7769bB8f84d5/sources/DimoStaking.sol
Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public virtual { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
13,223,726
./partial_match/97/0xCFa43e2207D50bB8a8652c4b4191AccEfDbDD87E/sources/LucaxUtilityToken.sol
Total number of tokens in existence/
function totalSupply() public override view returns (uint256) { return _totalSupply; }
11,443,677
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; // (Uni|Pancake)Swap libs are interchangeable import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol"; import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; /* For lines that are marked ERC20 Token Standard, learn more at https://eips.ethereum.org/EIPS/eip-20. */ contract ERC20Deflationary is Context, IERC20, Ownable { // Keeps track of balances for address that are included in receiving reward. mapping (address => uint256) private _reflectionBalances; // Keeps track of balances for address that are excluded from receiving reward. mapping (address => uint256) private _tokenBalances; // Keeps track of which address are excluded from fee. mapping (address => bool) private _isExcludedFromFee; // Keeps track of which address are excluded from reward. mapping (address => bool) private _isExcludedFromReward; // An array of addresses that are excluded from reward. address[] private _excludedFromReward; // ERC20 Token Standard mapping (address => mapping (address => uint256)) private _allowances; // Liquidity pool provider router IUniswapV2Router02 internal _uniswapV2Router; // This Token and WETH pair contract address. address internal _uniswapV2Pair; // Where burnt tokens are sent to. This is an address that no one can have accesses to. address private constant burnAccount = 0x000000000000000000000000000000000000dEaD; /* Tax rate = (_taxXXX / 10**_tax_XXXDecimals) percent. For example: if _taxBurn is 1 and _taxBurnDecimals is 2. Tax rate = 0.01% If you want tax rate for burn to be 5% for example, set _taxBurn to 5 and _taxBurnDecimals to 0. 5 * (10 ** 0) = 5 */ // Decimals of taxBurn. Used for have tax less than 1%. uint8 private _taxBurnDecimals; // Decimals of taxReward. Used for have tax less than 1%. uint8 private _taxRewardDecimals; // Decimals of taxLiquify. Used for have tax less than 1%. uint8 private _taxLiquifyDecimals; // This percent of a transaction will be burnt. uint8 private _taxBurn; // This percent of a transaction will be redistribute to all holders. uint8 private _taxReward; // This percent of a transaction will be added to the liquidity pool. More details at https://github.com/Sheldenshi/ERC20Deflationary. uint8 private _taxLiquify; // ERC20 Token Standard uint8 private _decimals; // ERC20 Token Standard uint256 private _totalSupply; // Current supply:= total supply - burnt tokens uint256 private _currentSupply; // A number that helps distributing fees to all holders respectively. uint256 private _reflectionTotal; // Total amount of tokens rewarded / distributing. uint256 private _totalRewarded; // Total amount of tokens burnt. uint256 private _totalBurnt; // Total amount of tokens locked in the LP (this token and WETH pair). uint256 private _totalTokensLockedInLiquidity; // Total amount of ETH locked in the LP (this token and WETH pair). uint256 private _totalETHLockedInLiquidity; // A threshold for swap and liquify. uint256 private _minTokensBeforeSwap; // ERC20 Token Standard string private _name; // ERC20 Token Standard string private _symbol; // Whether a previous call of SwapAndLiquify process is still in process. bool private _inSwapAndLiquify; bool private _autoSwapAndLiquifyEnabled; bool private _autoBurnEnabled; bool private _rewardEnabled; // Prevent reentrancy. modifier lockTheSwap { require(!_inSwapAndLiquify, "Currently in swap and liquify."); _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } // Return values of _getValues function. struct ValuesFromAmount { // Amount of tokens for to transfer. uint256 amount; // Amount tokens charged for burning. uint256 tBurnFee; // Amount tokens charged to reward. uint256 tRewardFee; // Amount tokens charged to add to liquidity. uint256 tLiquifyFee; // Amount tokens after fees. uint256 tTransferAmount; // Reflection of amount. uint256 rAmount; // Reflection of burn fee. uint256 rBurnFee; // Reflection of reward fee. uint256 rRewardFee; // Reflection of liquify fee. uint256 rLiquifyFee; // Reflection of transfer amount. uint256 rTransferAmount; } /* Events */ event Burn(address from, uint256 amount); event TaxBurnUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxRewardUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxLiquifyUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event MinTokensBeforeSwapUpdated(uint256 previous, uint256 current); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensAddedToLiquidity ); event ExcludeAccountFromReward(address account); event IncludeAccountInReward(address account); event ExcludeAccountFromFee(address account); event IncludeAccountInFee(address account); event EnabledAutoBurn(); event EnabledReward(); event EnabledAutoSwapAndLiquify(); event DisabledAutoBurn(); event DisabledReward(); event DisabledAutoSwapAndLiquify(); event Airdrop(uint256 amount); constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 tokenSupply_) { // Sets the values for `name`, `symbol`, `totalSupply`, `currentSupply`, and `rTotal`. _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = tokenSupply_ * (10 ** decimals_); _currentSupply = _totalSupply; _reflectionTotal = (~uint256(0) - (~uint256(0) % _totalSupply)); // Mint _reflectionBalances[_msgSender()] = _reflectionTotal; // exclude owner and this contract from fee. excludeAccountFromFee(owner()); excludeAccountFromFee(address(this)); // exclude owner, burnAccount, and this contract from receiving rewards. _excludeAccountFromReward(owner()); _excludeAccountFromReward(burnAccount); _excludeAccountFromReward(address(this)); emit Transfer(address(0), _msgSender(), _totalSupply); } // allow the contract to receive ETH receive() external payable {} /** * @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`). * * 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 Returns the address of this token and WETH pair. */ function uniswapV2Pair() public view virtual returns (address) { return _uniswapV2Pair; } /** * @dev Returns the current burn tax. */ function taxBurn() public view virtual returns (uint8) { return _taxBurn; } /** * @dev Returns the current reward tax. */ function taxReward() public view virtual returns (uint8) { return _taxReward; } /** * @dev Returns the current liquify tax. */ function taxLiquify() public view virtual returns (uint8) { return _taxLiquify; } /** * @dev Returns the current burn tax decimals. */ function taxBurnDecimals() public view virtual returns (uint8) { return _taxBurnDecimals; } /** * @dev Returns the current reward tax decimals. */ function taxRewardDecimals() public view virtual returns (uint8) { return _taxRewardDecimals; } /** * @dev Returns the current liquify tax decimals. */ function taxLiquifyDecimals() public view virtual returns (uint8) { return _taxLiquifyDecimals; } /** * @dev Returns true if auto burn feature is enabled. */ function autoBurnEnabled() public view virtual returns (bool) { return _autoBurnEnabled; } /** * @dev Returns true if reward feature is enabled. */ function rewardEnabled() public view virtual returns (bool) { return _rewardEnabled; } /** * @dev Returns true if auto swap and liquify feature is enabled. */ function autoSwapAndLiquifyEnabled() public view virtual returns (bool) { return _autoSwapAndLiquifyEnabled; } /** * @dev Returns the threshold before swap and liquify. */ function minTokensBeforeSwap() external view virtual returns (uint256) { return _minTokensBeforeSwap; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns current supply of the token. * (currentSupply := totalSupply - totalBurnt) */ function currentSupply() external view virtual returns (uint256) { return _currentSupply; } /** * @dev Returns the total number of tokens burnt. */ function totalBurnt() external view virtual returns (uint256) { return _totalBurnt; } /** * @dev Returns the total number of tokens locked in the LP. */ function totalTokensLockedInLiquidity() external view virtual returns (uint256) { return _totalTokensLockedInLiquidity; } /** * @dev Returns the total number of ETH locked in the LP. */ function totalETHLockedInLiquidity() external view virtual returns (uint256) { return _totalETHLockedInLiquidity; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { if (_isExcludedFromReward[account]) return _tokenBalances[account]; return tokenFromReflection(_reflectionBalances[account]); } /** * @dev Returns whether an account is excluded from reward. */ function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedFromReward[account]; } /** * @dev Returns whether an account is excluded from fee. */ function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[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); require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Burn} event indicating the amount burnt. * Emits a {Transfer} event with `to` set to the burn 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 != burnAccount, "ERC20: burn from the burn address"); uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); uint256 rAmount = _getRAmount(amount); // Transfer from account to the burnAccount if (_isExcludedFromReward[account]) { _tokenBalances[account] -= amount; } _reflectionBalances[account] -= rAmount; _tokenBalances[burnAccount] += amount; _reflectionBalances[burnAccount] += rAmount; _currentSupply -= amount; _totalBurnt += amount; emit Burn(account, amount); emit Transfer(account, burnAccount, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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"); ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]); if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferFromExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferToExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferStandard(sender, recipient, values); } else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferBothExcluded(sender, recipient, values); } else { _transferStandard(sender, recipient, values); } emit Transfer(sender, recipient, values.tTransferAmount); if (!_isExcludedFromFee[sender]) { _afterTokenTransfer(values); } } /** * @dev Performs all the functionalities that are enabled. */ function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual { // Burn if (_autoBurnEnabled) { _tokenBalances[address(this)] += values.tBurnFee; _reflectionBalances[address(this)] += values.rBurnFee; _approve(address(this), _msgSender(), values.tBurnFee); burnFrom(address(this), values.tBurnFee); } // Reflect if (_rewardEnabled) { _distributeFee(values.rRewardFee, values.tRewardFee); } // Add to liquidity pool if (_autoSwapAndLiquifyEnabled) { // add liquidity fee to this contract. _tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; uint256 contractBalance = _tokenBalances[address(this)]; // whether the current contract balances makes the threshold to swap and liquify. bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap; if (overMinTokensBeforeSwap && !_inSwapAndLiquify && _msgSender() != _uniswapV2Pair && _autoSwapAndLiquifyEnabled ) { swapAndLiquify(contractBalance); } } } /** * @dev Performs transfer between two accounts that are both included in receiving reward. */ function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an included account to an excluded account. * (included and excluded from receiving reward.) */ function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an excluded account to an included account. * (included and excluded from receiving reward.) */ function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer between two accounts that are both excluded in receiving reward. */ function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Destroys `amount` tokens from the caller. * */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } /** * @dev Excludes an account from receiving reward. * * Emits a {ExcludeAccountFromReward} event. * * Requirements: * * - `account` is included in receiving reward. */ function _excludeAccountFromReward(address account) internal { require(!_isExcludedFromReward[account], "Account is already excluded."); if(_reflectionBalances[account] > 0) { _tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); emit ExcludeAccountFromReward(account); } /** * @dev Includes an account from receiving reward. * * Emits a {IncludeAccountInReward} event. * * Requirements: * * - `account` is excluded in receiving reward. */ function _includeAccountInReward(address account) internal { require(_isExcludedFromReward[account], "Account is already included."); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tokenBalances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } emit IncludeAccountInReward(account); } /** * @dev Excludes an account from fee. * * Emits a {ExcludeAccountFromFee} event. * * Requirements: * * - `account` is included in fee. */ function excludeAccountFromFee(address account) internal { require(!_isExcludedFromFee[account], "Account is already excluded."); _isExcludedFromFee[account] = true; emit ExcludeAccountFromFee(account); } /** * @dev Includes an account from fee. * * Emits a {IncludeAccountFromFee} event. * * Requirements: * * - `account` is excluded in fee. */ function includeAccountInFee(address account) internal { require(_isExcludedFromFee[account], "Account is already included."); _isExcludedFromFee[account] = false; emit IncludeAccountInFee(account); } /** * @dev Airdrop tokens to all holders that are included from reward. * Requirements: * - the caller must have a balance of at least `amount`. */ function airdrop(uint256 amount) public { address sender = _msgSender(); //require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); require(balanceOf(sender) >= amount, "The caller must have balance >= amount."); ValuesFromAmount memory values = _getValues(amount, false); if (_isExcludedFromReward[sender]) { _tokenBalances[sender] -= values.amount; } _reflectionBalances[sender] -= values.rAmount; _reflectionTotal = _reflectionTotal - values.rAmount; _totalRewarded += amount ; emit Airdrop(amount); } /** * @dev Returns the reflected amount of a token. * Requirements: * - `amount` must be less than total supply. */ function reflectionFromToken(uint256 amount, bool deductTransferFee) internal view returns(uint256) { require(amount <= _totalSupply, "Amount must be less than supply"); ValuesFromAmount memory values = _getValues(amount, deductTransferFee); return values.rTransferAmount; } /** * @dev Used to figure out the balance after reflection. * Requirements: * - `rAmount` must be less than reflectTotal. */ function tokenFromReflection(uint256 rAmount) internal view returns(uint256) { require(rAmount <= _reflectionTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } /** * @dev Swap half of contract's token balance for ETH, * and pair it up with the other half to add to the * liquidity pool. * * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth, * the amount of ETH added to the LP, and the amount of tokens added to the LP. */ function swapAndLiquify(uint256 contractBalance) private lockTheSwap { // Split the contract balance into two halves. uint256 tokensToSwap = contractBalance / 2; uint256 tokensAddToLiquidity = contractBalance - tokensToSwap; // Contract's current ETH balance. uint256 initialBalance = address(this).balance; // Swap half of the tokens to ETH. swapTokensForEth(tokensToSwap); // Figure out the exact amount of tokens received from swapping. uint256 ethAddToLiquify = address(this).balance - initialBalance; // Add to the LP of this token and WETH pair (half ETH and half this token). addLiquidity(ethAddToLiquify, tokensAddToLiquidity); _totalETHLockedInLiquidity += address(this).balance - initialBalance; _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this)); emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity); } /** * @dev Swap `amount` tokens for ETH. * * Emits {Transfer} event. From this contract to the token and WETH Pair. */ function swapTokensForEth(uint256 amount) private { // Generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), // this contract will receive the eth that were swapped from the token block.timestamp + 60 * 1000 ); } /** * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP. * Depends on the current rate for the pair between this token and WETH, * `ethAmount` and `tokenAmount` might not match perfectly. * Dust(leftover) ETH or token will be refunded to this contract * (usually very small quantity). * * Emits {Transfer} event. From this contract to the token and WETH Pai. */ function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); } /** * @dev Distribute the `tRewardFee` tokens to all holders that are included in receiving reward. * amount received is based on how many token one owns. */ function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private { // This would decrease rate, thus increase amount reward receive based on one's balance. _reflectionTotal = _reflectionTotal - rRewardFee; _totalRewarded += tRewardFee; } /** * @dev Returns fees and transfer amount in both tokens and reflections. * tXXXX stands for tokenXXXX * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) { ValuesFromAmount memory values; values.amount = amount; _getTValues(values, deductTransferFee); _getRValues(values, deductTransferFee); return values; } /** * @dev Adds fees and transfer amount in tokens to `values`. * tXXXX stands for tokenXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private { if (deductTransferFee) { values.tTransferAmount = values.amount; } else { // calculate fee values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals); values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals); values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals); // amount after fee values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee; } } /** * @dev Adds fees and transfer amount in reflection to `values`. * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private { uint256 currentRate = _getRate(); values.rAmount = values.amount * currentRate; if (deductTransferFee) { values.rTransferAmount = values.rAmount; } else { values.rAmount = values.amount * currentRate; values.rBurnFee = values.tBurnFee * currentRate; values.rRewardFee = values.tRewardFee * currentRate; values.rLiquifyFee = values.tLiquifyFee * currentRate; values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee; } } /** * @dev Returns `amount` in reflection. */ function _getRAmount(uint256 amount) private view returns (uint256) { uint256 currentRate = _getRate(); return amount * currentRate; } /** * @dev Returns the current reflection rate. */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } /** * @dev Returns the current reflection supply and token supply. */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _reflectionTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply); rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]]; tSupply = tSupply - _tokenBalances[_excludedFromReward[i]]; } if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply); return (rSupply, tSupply); } /** * @dev Returns fee based on `amount` and `taxRate` */ function _calculateTax(uint256 amount, uint8 tax, uint8 taxDecimals_) private pure returns (uint256) { return amount * tax / (10 ** taxDecimals_) / (10 ** 2); } /* Owner functions */ /** * @dev Enables the auto burn feature. * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled. * * Emits a {EnabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(!_autoBurnEnabled, "Auto burn feature is already enabled."); require(taxBurn_ > 0, "Tax must be greater than 0."); require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _autoBurnEnabled = true; setTaxBurn(taxBurn_, taxBurnDecimals_); emit EnabledAutoBurn(); } /** * @dev Enables the reward feature. * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled. * * Emits a {EnabledReward} event. * * Requirements: * * - reward feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(!_rewardEnabled, "Reward feature is already enabled."); require(taxReward_ > 0, "Tax must be greater than 0."); require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _rewardEnabled = true; setTaxReward(taxReward_, taxRewardDecimals_); emit EnabledReward(); } /** * @dev Enables the auto swap and liquify feature. * Swaps half of transaction amount * `taxLiquify_` amount of tokens * to ETH and pair with the other half of tokens to the LP each transaction when enabled. * * Emits a {EnabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner { require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled."); require(taxLiquify_ > 0, "Tax must be greater than 0."); require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _minTokensBeforeSwap = minTokensBeforeSwap_; // init Router IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress); _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH()); if (_uniswapV2Pair == address(0)) { _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); } _uniswapV2Router = uniswapV2Router; // exclude uniswapV2Router from receiving reward. _excludeAccountFromReward(address(uniswapV2Router)); // exclude WETH and this Token Pair from receiving reward. _excludeAccountFromReward(_uniswapV2Pair); // exclude uniswapV2Router from paying fees. excludeAccountFromFee(address(uniswapV2Router)); // exclude WETH and this Token Pair from paying fees. excludeAccountFromFee(_uniswapV2Pair); // enable _autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify(); } /** * @dev Disables the auto burn feature. * * Emits a {DisabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be enabled. */ function disableAutoBurn() public onlyOwner { require(_autoBurnEnabled, "Auto burn feature is already disabled."); setTaxBurn(0, 0); _autoBurnEnabled = false; emit DisabledAutoBurn(); } /** * @dev Disables the reward feature. * * Emits a {DisabledReward} event. * * Requirements: * * - reward feature mush be enabled. */ function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); } /** * @dev Disables the auto swap and liquify feature. * * Emits a {DisabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be enabled. */ function disableAutoSwapAndLiquify() public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already disabled."); setTaxLiquify(0, 0); _autoSwapAndLiquifyEnabled = false; emit DisabledAutoSwapAndLiquify(); } /** * @dev Updates `_minTokensBeforeSwap` * * Emits a {MinTokensBeforeSwap} event. * * Requirements: * * - `minTokensBeforeSwap_` must be less than _currentSupply. */ function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner { require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply."); uint256 previous = _minTokensBeforeSwap; _minTokensBeforeSwap = minTokensBeforeSwap_; emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap); } /** * @dev Updates taxBurn * * Emits a {TaxBurnUpdate} event. * * Requirements: * * - auto burn feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function."); require(taxBurn_ + _taxReward + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxBurn; uint8 previousDecimals = _taxBurnDecimals; _taxBurn = taxBurn_; _taxBurnDecimals = taxBurnDecimals_; emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_); } /** * @dev Updates taxReward * * Emits a {TaxRewardUpdate} event. * * Requirements: * * - reward feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function."); require(_taxBurn + taxReward_ + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxReward; uint8 previousDecimals = _taxRewardDecimals; _taxReward = taxReward_; _taxBurnDecimals = taxRewardDecimals_; emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_); } /** * @dev Updates taxLiquify * * Emits a {TaxLiquifyUpdate} event. * * Requirements: * * - auto swap and liquify feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function."); require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high."); uint8 previousTax = _taxLiquify; uint8 previousDecimals = _taxLiquifyDecimals; _taxLiquify = taxLiquify_; _taxLiquifyDecimals = taxLiquifyDecimals_; emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_); } }
Disables the reward feature. Emits a {DisabledReward} event. Requirements: - reward feature mush be enabled./
function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); }
916,841
// contracts/GameItem.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./SocialGameToken.sol"; /** * @title Social Change Game Registry * @notice Smart Contract developed for the Harmony One Round 2 Hackathon on Gitcoin * @dev Contract that is used to register organisations for the social harmony games dapp. * Use a URI that points to a JSON object containing the information for each social harmony * organisation. Each org will have their own public keys registered in the registry. this can * be used to look up the social harmony games and the game token created for that public key. * * JSON format registering the organisation (note no validation of the JSON is made on the smart contract) { "organisation": "", "organisationBanner":"", // url of image "description": "", "story": "", "icon": "", "heroImages": [], // URL of images to show "publicKey": "", "contactDetails": { "email": "", "site": "", "twitter": "", "facebook": "", "phone": "" } } * * One public key may only own one organisation. The URI and JSON can be updated as required. For the DAPP, * IPFS is used to store the JSON dynamically. * * Note that at this point anyone can add an entry into the registry. Organisations are * verified by the registry owner (to be changed to allow multi-party verification). Verified organisations will * appear with a tick in the DAPP * * @author victaphu */ contract SocialHarmonyRegistry is Ownable, AccessControl { // mapping of address to URI of organisation mapping(address => string) private _tokenURIs; // list of organisations registered address[] public organisations; // mapping of verified organisations mapping(address => bool) private _verified; bytes32 public constant VERIFIER_GRANT_ROLE = "0x02"; // verify/revoke organisations uint256 public lastUpdated = 0; // latest update of the registry for caching purposes SocialGameToken public socialGameToken; // the token that this registry is connected to constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(VERIFIER_GRANT_ROLE, msg.sender); } function tokenURI(address organisation) public view virtual returns (string memory) { require( bytes(_tokenURIs[organisation]).length > 0, "Organisation not registered" ); return _tokenURIs[organisation]; } function registerURI(string memory uri) public { // updating the URI will also flag the item as unverified if (bytes(_tokenURIs[msg.sender]).length == 0) { organisations.push(msg.sender); } _tokenURIs[msg.sender] = uri; _verified[msg.sender] = false; lastUpdated ++; } function isVerified(address organisation) public view returns (bool verified_) { verified_ = _verified[organisation]; } function verifyOrganisation(address organisation) public onlyRole(VERIFIER_GRANT_ROLE) { require( bytes(_tokenURIs[organisation]).length > 0, "Organisation not registered" ); require( _verified[organisation] == false, "Organisation already verified" ); _verified[organisation] = true; lastUpdated ++; } function unverifyOrganisation(address organisation) public onlyRole(VERIFIER_GRANT_ROLE) { require( bytes(_tokenURIs[organisation]).length > 0, "Organisation not registered" ); require( _verified[organisation] == true, "Organisation already unverified" ); _verified[organisation] = false; lastUpdated ++; } function getOrgsCount() public view returns (uint256 count) { count = organisations.length; } function getOrgs() public view returns (address[] memory orgs) { orgs = organisations; } function getURIs(uint256 start, uint256 pageSize) public view returns (address[] memory orgs, string[] memory orgURIs, bool[] memory verified) { require(start >= 0 && pageSize > 0, "invalid inputs to getURIs, page size invalid"); require( (start + pageSize) <= organisations.length, "invalid input to getURIs" ); address[] memory orgs_ = new address[](pageSize); string[] memory orgURIs_ = new string[](pageSize); bool[] memory verified_ = new bool[](pageSize); for ( uint256 i = start; i < start + pageSize && i < organisations.length; ++i ) { orgs_[i - start] = organisations[i]; orgURIs_[i - start] = _tokenURIs[organisations[i]]; verified_[i - start] = _verified[organisations[i]]; } orgs = orgs_; orgURIs = orgURIs_; verified = verified_; } }
updating the URI will also flag the item as unverified
function registerURI(string memory uri) public { if (bytes(_tokenURIs[msg.sender]).length == 0) { organisations.push(msg.sender); } _tokenURIs[msg.sender] = uri; _verified[msg.sender] = false; lastUpdated ++; }
6,436,303
./partial_match/1/0xc8a2ADC4261c6b669CdFf69E717E77C9cFeB420d/sources/src/contracts/GovernanceCore.sol
@inheritdoc IGovernanceCore
function getPowerStrategy() external view returns (IGovernancePowerStrategy) { return _powerStrategy; }
15,500,865
./full_match/5/0xA18817e452d5b5913A28fB1a9d1257aF98b79059/sources/contracts/messaging/connectors/SpokeConnector.sol
This is either called by the Connector (AKA `this`) on the spoke (L2) chain after retrieving latest `aggregateRoot` from the AMB (sourced from mainnet) OR called by the AMB directly. Must check the msg.sender on the origin chain to ensure only the root manager is passing these roots./
function receiveAggregateRoot(bytes32 _newRoot) internal { require(_newRoot != bytes32(""), "new root empty"); require(pendingAggregateRoots[_newRoot] == 0, "root already pending"); require(!provenAggregateRoots[_newRoot], "root already proven"); pendingAggregateRoots[_newRoot] = block.number; emit AggregateRootReceived(_newRoot); }
1,923,906
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/utils/EnumerableSet.sol'; import 'maci-contracts/sol/MACI.sol'; import 'maci-contracts/sol/MACISharedObjs.sol'; import 'maci-contracts/sol/gatekeepers/SignUpGatekeeper.sol'; import 'maci-contracts/sol/initialVoiceCreditProxy/InitialVoiceCreditProxy.sol'; import './userRegistry/IUserRegistry.sol'; import './recipientRegistry/IRecipientRegistry.sol'; import './MACIFactory.sol'; import './FundingRound.sol'; contract FundingRoundFactory is Ownable, MACISharedObjs { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for ERC20; // State address public coordinator; ERC20 public nativeToken; MACIFactory public maciFactory; IUserRegistry public userRegistry; IRecipientRegistry public recipientRegistry; PubKey public coordinatorPubKey; EnumerableSet.AddressSet private fundingSources; FundingRound[] private rounds; // Events event FundingSourceAdded(address _source); event FundingSourceRemoved(address _source); event RoundStarted(address _round); event RoundFinalized(address _round); event TokenChanged(address _token); event CoordinatorChanged(address _coordinator); constructor( MACIFactory _maciFactory ) public { maciFactory = _maciFactory; } /** * @dev Set registry of verified users. * @param _userRegistry Address of a user registry. */ function setUserRegistry(IUserRegistry _userRegistry) external onlyOwner { userRegistry = _userRegistry; } /** * @dev Set recipient registry. * @param _recipientRegistry Address of a recipient registry. */ function setRecipientRegistry(IRecipientRegistry _recipientRegistry) external onlyOwner { recipientRegistry = _recipientRegistry; (,, uint256 maxVoteOptions) = maciFactory.maxValues(); recipientRegistry.setMaxRecipients(maxVoteOptions); } /** * @dev Add matching funds source. * @param _source Address of a funding source. */ function addFundingSource(address _source) external onlyOwner { bool result = fundingSources.add(_source); require(result, 'Factory: Funding source already added'); emit FundingSourceAdded(_source); } /** * @dev Remove matching funds source. * @param _source Address of the funding source. */ function removeFundingSource(address _source) external onlyOwner { bool result = fundingSources.remove(_source); require(result, 'Factory: Funding source not found'); emit FundingSourceRemoved(_source); } function getCurrentRound() public view returns (FundingRound _currentRound) { if (rounds.length == 0) { return FundingRound(address(0)); } return rounds[rounds.length - 1]; } function setMaciParameters( uint8 _stateTreeDepth, uint8 _messageTreeDepth, uint8 _voteOptionTreeDepth, uint8 _tallyBatchSize, uint8 _messageBatchSize, SnarkVerifier _batchUstVerifier, SnarkVerifier _qvtVerifier, uint256 _signUpDuration, uint256 _votingDuration ) external onlyOwner { maciFactory.setMaciParameters( _stateTreeDepth, _messageTreeDepth, _voteOptionTreeDepth, _tallyBatchSize, _messageBatchSize, _batchUstVerifier, _qvtVerifier, _signUpDuration, _votingDuration ); } /** * @dev Deploy new funding round. */ function deployNewRound() external onlyOwner { require(maciFactory.owner() == address(this), 'Factory: MACI factory is not owned by FR factory'); require(address(userRegistry) != address(0), 'Factory: User registry is not set'); require(address(recipientRegistry) != address(0), 'Factory: Recipient registry is not set'); require(address(nativeToken) != address(0), 'Factory: Native token is not set'); require(coordinator != address(0), 'Factory: No coordinator'); FundingRound currentRound = getCurrentRound(); require( address(currentRound) == address(0) || currentRound.isFinalized(), 'Factory: Current round is not finalized' ); // Make sure that the max number of recipients is set correctly (,, uint256 maxVoteOptions) = maciFactory.maxValues(); recipientRegistry.setMaxRecipients(maxVoteOptions); // Deploy funding round and MACI contracts FundingRound newRound = new FundingRound( nativeToken, userRegistry, recipientRegistry, coordinator ); rounds.push(newRound); MACI maci = maciFactory.deployMaci( SignUpGatekeeper(newRound), InitialVoiceCreditProxy(newRound), coordinator, coordinatorPubKey ); newRound.setMaci(maci); emit RoundStarted(address(newRound)); } /** * @dev Get total amount of matching funds. */ function getMatchingFunds(ERC20 token) external view returns (uint256) { uint256 matchingPoolSize = token.balanceOf(address(this)); for (uint256 index = 0; index < fundingSources.length(); index++) { address fundingSource = fundingSources.at(index); uint256 allowance = token.allowance(fundingSource, address(this)); uint256 balance = token.balanceOf(fundingSource); uint256 contribution = allowance < balance ? allowance : balance; matchingPoolSize += contribution; } return matchingPoolSize; } /** * @dev Transfer funds from matching pool to current funding round and finalize it. * @param _totalSpent Total amount of spent voice credits. * @param _totalSpentSalt The salt. */ function transferMatchingFunds( uint256 _totalSpent, uint256 _totalSpentSalt ) external onlyOwner { FundingRound currentRound = getCurrentRound(); require(address(currentRound) != address(0), 'Factory: Funding round has not been deployed'); ERC20 roundToken = currentRound.nativeToken(); // Factory contract is the default funding source uint256 matchingPoolSize = roundToken.balanceOf(address(this)); if (matchingPoolSize > 0) { roundToken.safeTransfer(address(currentRound), matchingPoolSize); } // Pull funds from other funding sources for (uint256 index = 0; index < fundingSources.length(); index++) { address fundingSource = fundingSources.at(index); uint256 allowance = roundToken.allowance(fundingSource, address(this)); uint256 balance = roundToken.balanceOf(fundingSource); uint256 contribution = allowance < balance ? allowance : balance; if (contribution > 0) { roundToken.safeTransferFrom(fundingSource, address(currentRound), contribution); } } currentRound.finalize(_totalSpent, _totalSpentSalt); emit RoundFinalized(address(currentRound)); } /** * @dev Cancel current round. */ function cancelCurrentRound() external onlyOwner { FundingRound currentRound = getCurrentRound(); require(address(currentRound) != address(0), 'Factory: Funding round has not been deployed'); require(!currentRound.isFinalized(), 'Factory: Current round is finalized'); currentRound.cancel(); emit RoundFinalized(address(currentRound)); } /** * @dev Set token in which contributions are accepted. * @param _token Address of the token contract. */ function setToken(address _token) external onlyOwner { nativeToken = ERC20(_token); emit TokenChanged(_token); } /** * @dev Set coordinator's address and public key. * @param _coordinator Coordinator's address. * @param _coordinatorPubKey Coordinator's public key. */ function setCoordinator( address _coordinator, PubKey memory _coordinatorPubKey ) external onlyOwner { coordinator = _coordinator; coordinatorPubKey = _coordinatorPubKey; emit CoordinatorChanged(_coordinator); } function coordinatorQuit() external onlyCoordinator { // The fact that they quit is obvious from // the address being 0x0 coordinator = address(0); coordinatorPubKey = PubKey(0, 0); FundingRound currentRound = getCurrentRound(); if (address(currentRound) != address(0) && !currentRound.isFinalized()) { currentRound.cancel(); emit RoundFinalized(address(currentRound)); } emit CoordinatorChanged(address(0)); } modifier onlyCoordinator() { require(msg.sender == coordinator, 'Factory: Sender is not the coordinator'); _; } }
Set coordinator's address and public key. _coordinator Coordinator's address. _coordinatorPubKey Coordinator's public key./
function setCoordinator( address _coordinator, PubKey memory _coordinatorPubKey ) external onlyOwner { coordinator = _coordinator; coordinatorPubKey = _coordinatorPubKey; emit CoordinatorChanged(_coordinator); }
14,027,307
pragma solidity ^0.4.24; /// @title New Child Kydy's Genes contract GeneSynthesisInterface { /// @dev boolean to check this is the contract we expect to be function isGeneSynthesis() public pure returns (bool); /** * @dev Synthesizes the genes of yin and yang Kydy, and returns the result as the child's genes. * @param gene1 genes of yin Kydy * @param gene2 genes of yang Kydy * @return the genes of the child */ function synthGenes(uint256 gene1, uint256 gene2) public returns (uint256); } /** * @title Part of KydyCore that manages special access controls. * @author VREX Lab Co., Ltd * @dev See the KydyCore contract documentation to understand how the various contracts are arranged. */ contract KydyAccessControl { /** * This contract defines access control for the following important roles of the Dyverse: * * - The CEO: The CEO can assign roles and change the addresses of the smart contracts. * It can also solely unpause the smart contract. * * - The CFO: The CFO can withdraw funds from the KydyCore and the auction contracts. * * - The COO: The COO can release Generation 0 Kydys and create promotional-type Kydys. * */ /// @dev Used when contract is upgraded. event ContractUpgrade(address newContract); // The assigned addresses of each role, as defined in this contract. address public ceoAddress; address public cfoAddress; address public cooAddress; /// @dev Checks if the contract is paused. When paused, most of the functions of this contract will also be stopped. bool public paused = false; /// @dev Access modifier for CEO-only modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Access modifier for CEO, CFO, COO modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == cooAddress ); _; } /** * @dev Assigns a new address to the CEO. Only the current CEO has the authority. * @param _newCEO The address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /** * @dev Assigns a new address to the CFO. Only the current CEO has the authority. * @param _newCFO The address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /** * @dev Assigns a new address to the COO. Only the current CEO has the authority. * @param _newCOO The address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** 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 to limit the damage. */ function pause() external 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. * @notice This is public rather than external so it can be called by * derived contracts. */ function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } contract ERC165Interface { /** * @notice Query if a contract implements an interface * @param interfaceID The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. * @return `true` if the contract implements `interfaceID` and * `interfaceID` is not 0xffffffff, `false` otherwise */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract ERC165 is ERC165Interface { /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // Every ERC-721 compliant contract must implement the ERC721 and ERC165 interfaces. /** * @title ERC-721 Non-Fungible Token Standard * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x80ac58cd. */ contract ERC721Basic is ERC165 { // Below is MUST /** * @dev This emits when ownership of any NFT changes by any mechanism. * This event emits when NFTs are created (`from` == 0) and destroyed * (`to` == 0). Exception: during contract creation, any number of NFTs * may be created and assigned without emitting Transfer. At the time of * any transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /** * @dev This emits when the approved address for an NFT is changed or * reaffirmed. The zero address indicates there is no approved address. * When a Transfer event emits, this also indicates that the approved * address for that NFT (if any) is reset to none. */ event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /** * @dev This emits when an operator is enabled or disabled for an owner. * The operator can manage all NFTs of the owner. */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @notice Count all NFTs assigned to an owner * @dev NFTs assigned to the zero address are considered invalid, and this * function throws for queries about the zero address. * @param _owner An address for whom to query the balance * @return The number of NFTs owned by `_owner`, possibly zero */ function balanceOf(address _owner) public view returns (uint256); /** * @notice Find the owner of an NFT * @dev NFTs assigned to zero address are considered invalid, and queries * about them do throw. * @param _tokenId The identifier for an NFT * @return The address of the owner of the NFT */ function ownerOf(uint256 _tokenId) public view returns (address); /** * @notice Transfers the ownership of an NFT from one address to another address * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. When transfer is complete, this function * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer * @param data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public; /** * @notice Transfers the ownership of an NFT from one address to another address * @dev This works identically to the other function with an extra data parameter, * except this function just sets data to "". * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; /** * @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE * TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE * THEY MAY BE PERMANENTLY LOST * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function transferFrom(address _from, address _to, uint256 _tokenId) public; /** * @notice Change or reaffirm the approved address for an NFT * @dev The zero address indicates there is no approved address. * Throws unless `msg.sender` is the current NFT owner, or an authorized * operator of the current owner. * @param _approved The new approved NFT controller * @param _tokenId The NFT to approve */ function approve(address _approved, uint256 _tokenId) external; /** * @notice Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s assets * @dev Emits the ApprovalForAll event. The contract MUST allow * multiple operators per owner. * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Get the approved address for a single NFT * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for * @return The approved address for this NFT, or the zero address if there is none */ function getApproved(uint256 _tokenId) public view returns (address); /** * @notice Query if an address is an authorized operator for another address * @param _owner The address that owns the NFTs * @param _operator The address that acts on behalf of the owner * @return True if `_operator` is an approved operator for `_owner`, false otherwise */ function isApprovedForAll(address _owner, address _operator) public view returns (bool); // Below is OPTIONAL // ERC721Metadata // The metadata extension is OPTIONAL for ERC-721 smart contracts (see "caveats", below). This allows your smart contract to be interrogated for its name and for details about the assets which your NFTs represent. /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x5b5e139f. */ /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /** * @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string); // ERC721Enumerable // The enumeration extension is OPTIONAL for ERC-721 smart contracts (see "caveats", below). This allows your contract to publish its full list of NFTs and make them discoverable. /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x780e9d63. */ /** * @notice Count NFTs tracked by this contract * @return A count of valid NFTs tracked by this contract, where each one of * them has an assigned and queryable owner not equal to the zero address */ function totalSupply() public view returns (uint256); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title The base contract of Dyverse. ERC-721 compliant. * @author VREX Lab Co., Ltd * @dev See the KydyCore contract for more info on details. */ contract KydyBase is KydyAccessControl, ERC721Basic { using SafeMath for uint256; using Address for address; /*** EVENT ***/ /** * @dev The Creation event takes place whenever a new Kydy is created via Synthesis or minted by the COO. */ event Created(address indexed owner, uint256 kydyId, uint256 yinId, uint256 yangId, uint256 genes); /*** DATA TYPES ***/ /** * @dev Every Kydy in the Dyverse is a copy of this structure. */ struct Kydy { // The Kydy's genetic code is stored into 256-bits and never changes. uint256 genes; // The timestamp of the block when this Kydy was created uint64 createdTime; // The timestamp of when this Kydy can synthesize again. uint64 rechargeEndBlock; // The ID of the parents (Yin, female, and Yang, male). It is 0 for Generation 0 Kydys. uint32 yinId; uint32 yangId; // The ID of the yang Kydy that the yin Kydy is creating with. uint32 synthesizingWithId; // The recharge index that represents the duration of the recharge for this Kydy. // After each synthesis, this increases by one for both yin and yang Kydys of the synthesis. uint16 rechargeIndex; // The generation index of this Kydy. The newly created Kydy takes the generation index of the parent // with a larger generation index. uint16 generation; } /*** CONSTANTS ***/ /** * @dev An array table of the recharge duration. Referred to as "creation time" for yin * and "synthesis recharge" for yang Kydys. Maximum duration is 4 days. */ uint32[14] public recharges = [ 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) ]; // An approximation of seconds between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /** * @dev This array contains the ID of every Kydy as an index. */ Kydy[] kydys; /** * @dev This maps each Kydy ID to the address of the owner. Every Kydy must have an owner, even Gen 0 Kydys. * You can view this mapping via `ownerOf()`. */ mapping (uint256 => address) internal kydyIndexToOwner; /** * @dev This maps the owner's address to the number of Kydys that the address owns. * You can view this mapping via `balanceOf()`. */ mapping (address => uint256) internal ownershipTokenCount; /** * @dev This maps transferring Kydy IDs to the the approved address to call safeTransferFrom(). * You can view this mapping via `getApproved()`. */ mapping (uint256 => address) internal kydyIndexToApproved; /** * @dev This maps KydyIDs to the address approved to synthesize via synthesizeWithAuto(). * You can view this mapping via `getSynthesizeApproved()`. */ mapping (uint256 => address) internal synthesizeAllowedToAddress; /** * @dev This maps the owner to operator approvals, for the usage of setApprovalForAll(). */ mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Returns the owner of the given Kydy ID. Required for ERC-721 compliance. * @param _tokenId uint256 ID of the Kydy in query * @return the address of the owner of the given Kydy ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = kydyIndexToOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns the approved address of the receiving owner for a Kydy ID. Required for ERC-721 compliance. * @param tokenId uint256 ID of the Kydy in query * @return the address of the approved, receiving owner for the given Kydy ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return kydyIndexToApproved[tokenId]; } /** * @dev Returns the synthesize approved address of the Kydy ID. * @param tokenId uint256 ID of the Kydy in query * @return the address of the synthesizing approved of the given Kydy ID */ function getSynthesizeApproved(uint256 tokenId) external view returns (address) { require(_exists(tokenId)); return synthesizeAllowedToAddress[tokenId]; } /** * @dev Returns whether an operator is approved by the owner. Required for ERC-721 compliance. * @param owner owner address to check whether it is approved * @param operator operator address to check whether it is approved * @return bool whether the operator is approved or not */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Sets or unsets the approval of the operator. Required for ERC-721 compliance. * @param to operator address to set the approval * @param approved the status to be set */ function setApprovalForAll(address to, bool approved) external { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /// @dev Assigns ownership of this Kydy to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to] = ownershipTokenCount[_to].add(1); // Transfers the ownership of this Kydy. kydyIndexToOwner[_tokenId] = _to; ownershipTokenCount[_from] = ownershipTokenCount[_from].sub(1); // After a transfer, synthesis allowance is also reset. delete synthesizeAllowedToAddress[_tokenId]; // Clears any previously approved transfer. delete kydyIndexToApproved[_tokenId]; // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /** * @dev Returns whether the given Kydy ID exists * @param _tokenId uint256 ID of the Kydy in query * @return whether the Kydy exists */ function _exists(uint256 _tokenId) internal view returns (bool) { address owner = kydyIndexToOwner[_tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer the Kydy ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the Kydy to be transferred * @return bool whether the msg.sender is approved */ function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender)); } /** * @dev Internal function to add a Kydy ID to the new owner's list. * @param _to address the new owner's address * @param _tokenId uint256 ID of the transferred Kydy */ function _addTokenTo(address _to, uint256 _tokenId) internal { // Checks if the owner of the Kydy is 0x0 before the transfer. require(kydyIndexToOwner[_tokenId] == address(0)); // Transfers the ownership to the new owner. kydyIndexToOwner[_tokenId] = _to; // Increases the total Kydy count of the new owner. ownershipTokenCount[_to] = ownershipTokenCount[_to].add(1); } /** * @dev Internal function to remove a Kydy ID from the previous owner's list. * @param _from address the previous owner's address * @param _tokenId uint256 ID of the transferred Kydy */ function _removeTokenFrom(address _from, uint256 _tokenId) internal { // Checks the current owner of the Kydy is '_from'. require(ownerOf(_tokenId) == _from); // Reduces the total Kydy count of the previous owner. ownershipTokenCount[_from] = ownershipTokenCount[_from].sub(1); // Deletes the transferred Kydy from the current owner's list. kydyIndexToOwner[_tokenId] = address(0); } /** * @dev Internal function to mint a new Kydy. * @param _to The address that owns the newly minted Kydy * @param _tokenId uint256 ID of the newly minted Kydy */ function _mint(address _to, uint256 _tokenId) internal { require(!_exists(_tokenId)); _addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to clear current approvals of a given Kydy ID. * @param _owner owner of the Kydy * @param _tokenId uint256 ID of the Kydy to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (kydyIndexToApproved[_tokenId] != address(0)) { kydyIndexToApproved[_tokenId] = address(0); } if (synthesizeAllowedToAddress[_tokenId] != address(0)) { synthesizeAllowedToAddress[_tokenId] = address(0); } } /** * @dev Internal function that creates a new Kydy and stores it. * @param _yinId The ID of the yin Kydy (zero for Generation 0 Kydy) * @param _yangId The ID of the yang Kydy (zero for Generation 0 Kydy) * @param _generation The generation number of the new Kydy. * @param _genes The Kydy's gene code * @param _owner The owner of this Kydy, must be non-zero (except for the ID 0) */ function _createKydy( uint256 _yinId, uint256 _yangId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { require(_yinId == uint256(uint32(_yinId))); require(_yangId == uint256(uint32(_yangId))); require(_generation == uint256(uint16(_generation))); // New Kydy's recharge index is its generation / 2. uint16 rechargeIndex = uint16(_generation / 2); if (rechargeIndex > 13) { rechargeIndex = 13; } Kydy memory _kyd = Kydy({ genes: _genes, createdTime: uint64(now), rechargeEndBlock: 0, yinId: uint32(_yinId), yangId: uint32(_yangId), synthesizingWithId: 0, rechargeIndex: rechargeIndex, generation: uint16(_generation) }); uint256 newbabyKydyId = kydys.push(_kyd) - 1; // Just in case. require(newbabyKydyId == uint256(uint32(newbabyKydyId))); // Emits the Created event. emit Created( _owner, newbabyKydyId, uint256(_kyd.yinId), uint256(_kyd.yangId), _kyd.genes ); // Here grants ownership, and also emits the Transfer event. _mint(_owner, newbabyKydyId); return newbabyKydyId; } // Any C-level roles can change the seconds per block function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < recharges[0]); secondsPerBlock = secs; } } /** * @notice This is MUST to be implemented. * A wallet/broker/auction application MUST implement the wallet interface if it will accept safe transfers. * @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. */ contract ERC721TokenReceiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `transfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` * unless throwing */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns (bytes4); } // File: contracts/lib/Strings.sol library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } /** * @title Part of the KydyCore contract that manages ownership, ERC-721 compliant. * @author VREX Lab Co., Ltd * @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * See the KydyCore contract documentation to understand how the various contracts are arranged. */ contract KydyOwnership is KydyBase { using Strings for string; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant _name = "Dyverse"; string public constant _symbol = "KYDY"; // Base Server Address for Token MetaData URI string internal tokenURIBase = "http://testapi.dyver.se/api/KydyMetadata/"; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721TokenReceiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant _InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ constructor() public { _registerInterface(_InterfaceId_ERC165); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Metadata); } /** * @dev Checks if a given address is the current owner of this Kydy. * @param _claimant the address which we want to query the ownership of the Kydy ID. * @param _tokenId Kydy id, only valid when > 0 */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kydyIndexToOwner[_tokenId] == _claimant; } /** * @dev Grants an approval to the given address for safeTransferFrom(), overwriting any * previous approval. Setting _approved to address(0) clears all transfer approval. * Note that _approve() does NOT emit the Approval event. This is intentional because * _approve() and safeTransferFrom() are used together when putting Kydys to the auction, * and there is no need to spam the log with Approval events in that case. */ function _approve(uint256 _tokenId, address _approved) internal { kydyIndexToApproved[_tokenId] = _approved; } /** * @dev Transfers a Kydy owned by this contract to the specified address. * Used to rescue lost Kydys. (There is no "proper" flow where this contract * should be the owner of any Kydy. This function exists for us to reassign * the ownership of Kydys that users may have accidentally sent to our address.) * @param _kydyId ID of the lost Kydy * @param _recipient address to send the Kydy to */ function rescueLostKydy(uint256 _kydyId, address _recipient) external onlyCOO whenNotPaused { require(_owns(this, _kydyId)); _transfer(this, _recipient, _kydyId); } /** * @dev Gets the number of Kydys owned by the given address. * Required for ERC-721 compliance. * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownershipTokenCount[_owner]; } /** * @dev Approves another address to transfer the given Kydy ID. * The zero address indicates that there is no approved address. * There can only be one approved address per Kydy at a given time. * Can only be called by the Kydy owner or an approved operator. * Required for ERC-721 compliance. * @param to address to be approved for the given Kydy ID * @param tokenId uint256 ID of the Kydy to be approved */ function approve(address to, uint256 tokenId) external whenNotPaused { address owner = ownerOf(tokenId); require(to != owner); // Owner or approved operator by owner can approve the another address // to transfer the Kydy. require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); // Approves the given address. _approve(tokenId, to); // Emits the Approval event. emit Approval(owner, to, tokenId); } /** * @dev Transfers the ownership of the Kydy to another address. * Usage of this function is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg sender to be the owner, approved, or operator. * Required for ERC-721 compliance. * @param from current owner of the Kydy * @param to address to receive the ownership of the given Kydy ID * @param tokenId uint256 ID of the Kydy to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public whenNotPaused { // Checks the caller is the owner or approved one or an operator. require(_isApprovedOrOwner(msg.sender, tokenId)); // Safety check to prevent from transferring Kydy to 0x0 address. require(to != address(0)); // Clears approval from current owner. _clearApproval(from, tokenId); // Resets the ownership of this Kydy from current owner and sets it to 0x0. _removeTokenFrom(from, tokenId); // Grants the ownership of this Kydy to new owner. _addTokenTo(to, tokenId); // Emits the Transfer event. emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given Kydy to another address. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * Otherwise, the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator. * Required for ERC-721 compliance. * @param from current owner of the Kydy * @param to address to receive the ownership of the given Kydy ID * @param tokenId uint256 ID of the Kydy to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given Kydy to another address. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * Otherwise, the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator. * Required for ERC-721 compliance. * @param from current owner of the Kydy * @param to address to receive the ownership of the given Kydy ID * @param tokenId uint256 ID of the Kydy to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * This function is not executed if the target address is not a contract. * @param _from address representing the previous owner of the given Kydy ID * @param _to target address that will receive the Kydys * @param _tokenId uint256 ID of the Kydy to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Gets the token name. * Required for ERC721Metadata compliance. * @return string representing the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token symbol. * Required for ERC721Metadata compliance. * @return string representing the token symbol */ function symbol() external view returns (string) { return _symbol; } /** * @dev Returns an URI for a given Kydy ID. * Throws if the token ID does not exist. May return an empty string. * Required for ERC721Metadata compliance. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); return Strings.strConcat( tokenURIBase, Strings.uint2str(tokenId) ); } /** * @dev Gets the total amount of Kydys stored in the contract * @return uint256 representing the total amount of Kydys */ function totalSupply() public view returns (uint256) { return kydys.length - 1; } /** * @notice Returns a list of all Kydy IDs assigned to an address. * @param _owner The owner whose Kydys we are interested in. * @dev This function MUST NEVER be called by smart contract code. It's pretty * expensive (it looks into the entire Kydy array looking for Kydys belonging to owner), * and it also returns a dynamic array, which is only supported for web3 calls, and * not contract-to-contract calls. */ function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalKydys = totalSupply(); uint256 resultIndex = 0; // All Kydys have IDs starting at 1 and increasing sequentially up to the totalKydy count. uint256 kydyId; for (kydyId = 1; kydyId <= totalKydys; kydyId++) { if (kydyIndexToOwner[kydyId] == _owner) { result[resultIndex] = kydyId; resultIndex++; } } return result; } } } /** * @title This manages synthesis and creation of Kydys. * @author VREX Lab Co., Ltd * @dev Please reference the KydyCore contract for details. */ contract KydySynthesis is KydyOwnership { /** * @dev The Creating event is emitted when two Kydys synthesize and the creation * timer begins by the yin. */ event Creating(address owner, uint256 yinId, uint256 yangId, uint256 rechargeEndBlock); /** * @notice The minimum payment required for synthesizeWithAuto(). This fee is for * the gas cost paid by whoever calls bringKydyHome(), and can be updated by the COO address. */ uint256 public autoCreationFee = 14 finney; // Number of the Kydys that are creating a new Kydy. uint256 public creatingKydys; /** * @dev The address of the sibling contract that mixes and combines genes of the two parent Kydys. */ GeneSynthesisInterface public geneSynthesis; /** * @dev Updates the address of the genetic contract. Only CEO may call this function. * @param _address An address of the new GeneSynthesis contract instance. */ function setGeneSynthesisAddress(address _address) external onlyCEO { GeneSynthesisInterface candidateContract = GeneSynthesisInterface(_address); // Verifies that the contract is valid. require(candidateContract.isGeneSynthesis()); // Sets the new GeneSynthesis contract address. geneSynthesis = candidateContract; } /** * @dev Checks that the Kydy is able to synthesize. */ function _isReadyToSynthesize(Kydy _kyd) internal view returns (bool) { // Double-checking if there is any pending creation event. return (_kyd.synthesizingWithId == 0) && (_kyd.rechargeEndBlock <= uint64(block.number)); } /** * @dev Checks if a yang Kydy has been approved to synthesize with this yin Kydy. */ function _isSynthesizingAllowed(uint256 _yangId, uint256 _yinId) internal view returns (bool) { address yinOwner = kydyIndexToOwner[_yinId]; address yangOwner = kydyIndexToOwner[_yangId]; return (yinOwner == yangOwner || synthesizeAllowedToAddress[_yangId] == yinOwner); } /** * @dev Sets the rechargeEndTime for the given Kydy, based on its current rechargeIndex. * The rechargeIndex increases until it hits the cap. * @param _kyd A reference to the Kydy that needs its timer to be started. */ function _triggerRecharge(Kydy storage _kyd) internal { // Computes the approximation of the end of recharge time in blocks (based on current rechargeIndex). _kyd.rechargeEndBlock = uint64((recharges[_kyd.rechargeIndex] / secondsPerBlock) + block.number); // Increases this Kydy's synthesizing count, and the cap is fixed at 12. if (_kyd.rechargeIndex < 12) { _kyd.rechargeIndex += 1; } } /** * @notice Grants approval to another user to synthesize with one of your Kydys. * @param _address The approved address of the yin Kydy that can synthesize with your yang Kydy. * @param _yangId Your kydy that _address can now synthesize with. */ function approveSynthesizing(address _address, uint256 _yangId) external whenNotPaused { require(_owns(msg.sender, _yangId)); synthesizeAllowedToAddress[_yangId] = _address; } /** * @dev Updates the minimum payment required for calling bringKydyHome(). Only COO * can call this function. */ function setAutoCreationFee(uint256 value) external onlyCOO { autoCreationFee = value; } /// @dev Checks if this Kydy is creating and if the creation period is complete. function _isReadyToBringKydyHome(Kydy _yin) private view returns (bool) { return (_yin.synthesizingWithId != 0) && (_yin.rechargeEndBlock <= uint64(block.number)); } /** * @notice Checks if this Kydy is able to synthesize * @param _kydyId reference the ID of the Kydy */ function isReadyToSynthesize(uint256 _kydyId) public view returns (bool) { require(_kydyId > 0); Kydy storage kyd = kydys[_kydyId]; return _isReadyToSynthesize(kyd); } /** * @dev Checks if the Kydy is currently creating. * @param _kydyId reference the ID of the Kydy */ function isCreating(uint256 _kydyId) public view returns (bool) { require(_kydyId > 0); return kydys[_kydyId].synthesizingWithId != 0; } /** * @dev Internal check to see if these yang and yin are a valid couple. * @param _yin A reference to the Kydy struct of the potential yin. * @param _yinId The yin's ID. * @param _yang A reference to the Kydy struct of the potential yang. * @param _yangId The yang's ID */ function _isValidCouple( Kydy storage _yin, uint256 _yinId, Kydy storage _yang, uint256 _yangId ) private view returns(bool) { // Kydy can't synthesize with itself. if (_yinId == _yangId) { return false; } // Kydys can't synthesize with their parents. if (_yin.yinId == _yangId || _yin.yangId == _yangId) { return false; } if (_yang.yinId == _yinId || _yang.yangId == _yinId) { return false; } // Skip sibling check for Gen 0 if (_yang.yinId == 0 || _yin.yinId == 0) { return true; } // Kydys can't synthesize with full or half siblings. if (_yang.yinId == _yin.yinId || _yang.yinId == _yin.yangId) { return false; } if (_yang.yangId == _yin.yinId || _yang.yangId == _yin.yangId) { return false; } return true; } /** * @dev Internal check to see if these yang and yin Kydys, connected via market, are a valid couple for synthesis. */ function _canSynthesizeWithViaAuction(uint256 _yinId, uint256 _yangId) internal view returns (bool) { Kydy storage yin = kydys[_yinId]; Kydy storage yang = kydys[_yangId]; return _isValidCouple(yin, _yinId, yang, _yangId); } /** * @dev Checks if the two Kydys can synthesize together, including checks for ownership and synthesizing approvals. * @param _yinId ID of the yin Kydy * @param _yangId ID of the yang Kydy */ function canSynthesizeWith(uint256 _yinId, uint256 _yangId) external view returns(bool) { require(_yinId > 0); require(_yangId > 0); Kydy storage yin = kydys[_yinId]; Kydy storage yang = kydys[_yangId]; return _isValidCouple(yin, _yinId, yang, _yangId) && _isSynthesizingAllowed(_yangId, _yinId); } /** * @dev Internal function to start synthesizing, when all the conditions are met */ function _synthesizeWith(uint256 _yinId, uint256 _yangId) internal { Kydy storage yang = kydys[_yangId]; Kydy storage yin = kydys[_yinId]; // Marks this yin as creating, and make note of who the yang Kydy is. yin.synthesizingWithId = uint32(_yangId); // Triggers the recharge for both parents. _triggerRecharge(yang); _triggerRecharge(yin); // Clears synthesizing permission for both parents, just in case. delete synthesizeAllowedToAddress[_yinId]; delete synthesizeAllowedToAddress[_yangId]; // When a Kydy starts creating, this number is increased. creatingKydys++; // Emits the Creating event. emit Creating(kydyIndexToOwner[_yinId], _yinId, _yangId, yin.rechargeEndBlock); } /** * @dev Synthesis between two approved Kydys. Requires a pre-payment of the fee to the first caller of bringKydyHome(). * @param _yinId ID of the Kydy which will be a yin (will start creation if successful) * @param _yangId ID of the Kydy which will be a yang (will begin its synthesizing cooldown if successful) */ function synthesizeWithAuto(uint256 _yinId, uint256 _yangId) external payable whenNotPaused { // Checks for pre-payment. require(msg.value >= autoCreationFee); // Caller must be the yin's owner. require(_owns(msg.sender, _yinId)); // Checks if the caller has valid authority for this synthesis require(_isSynthesizingAllowed(_yangId, _yinId)); // Gets a reference of the potential yin. Kydy storage yin = kydys[_yinId]; // Checks that the potential yin is ready to synthesize require(_isReadyToSynthesize(yin)); // Gets a reference of the potential yang. Kydy storage yang = kydys[_yangId]; // Checks that the potential yang is ready to synthesize require(_isReadyToSynthesize(yang)); // Checks that these Kydys are a valid couple. require(_isValidCouple( yin, _yinId, yang, _yangId )); // All checks passed! Yin Kydy starts creating. _synthesizeWith(_yinId, _yangId); } /** * @notice Let's bring the new Kydy to it's home! * @param _yinId A Kydy which is ready to bring the newly created Kydy to home. * @return The Kydy ID of the newly created Kydy. * @dev The newly created Kydy is transferred to the owner of the yin Kydy. Anyone is welcome to call this function. */ function bringKydyHome(uint256 _yinId) external whenNotPaused returns(uint256) { // Gets a reference of the yin from storage. Kydy storage yin = kydys[_yinId]; // Checks that the yin is a valid Kydy. require(yin.createdTime != 0); // Checks that the yin is in creation mode, and the creating period is over. require(_isReadyToBringKydyHome(yin)); // Gets a reference of the yang from storage. uint256 yangId = yin.synthesizingWithId; Kydy storage yang = kydys[yangId]; // Ascertains which has the higher generation number between the two parents. uint16 parentGen = yin.generation; if (yang.generation > yin.generation) { parentGen = yang.generation; } // The baby Kydy receives its genes uint256 childGenes = geneSynthesis.synthGenes(yin.genes, yang.genes); // The baby Kydy is now on blockchain address owner = kydyIndexToOwner[_yinId]; uint256 kydyId = _createKydy(_yinId, yin.synthesizingWithId, parentGen + 1, childGenes, owner); // Clears the synthesis status of the parents delete yin.synthesizingWithId; // When a baby Kydy is created, this number is decreased back. creatingKydys--; // Sends the fee to the person who called this. msg.sender.transfer(autoCreationFee); // Returns the new Kydy's ID. return kydyId; } } contract ERC721Holder is ERC721TokenReceiver { function onERC721Received(address, address, uint256, bytes) public returns (bytes4) { return this.onERC721Received.selector; } } /** * @title Base auction contract of the Dyverse * @author VREX Lab Co., Ltd * @dev Contains necessary functions and variables for the auction. * Inherits `ERC721Holder` contract which is the implementation of the `ERC721TokenReceiver`. * This is to accept safe transfers. */ contract AuctionBase is ERC721Holder { using SafeMath for uint256; // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) of NFT uint128 price; // Time when the auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721Basic public nonFungibleContract; // The amount owner takes from the sale, (in basis points, which are 1/100 of a percent). uint256 public ownerCut; // Maps token ID to it's corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 price); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address bidder); event AuctionCanceled(uint256 tokenId); /// @dev Disables sending funds to this contract. function() external {} /// @dev A modifier to check if the given value can fit in 64-bits. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= (2**64 - 1)); _; } /// @dev A modifier to check if the given value can fit in 128-bits. modifier canBeStoredWith128Bits(uint256 _value) { require(_value <= (2**128 - 1)); _; } /** * @dev Returns true if the claimant owns the token. * @param _claimant An address which to query the ownership of the token. * @param _tokenId ID of the token to query the owner of. */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /** * @dev Escrows the NFT. Grants the ownership of the NFT to this contract safely. * Throws if the escrow fails. * @param _owner Current owner of the token. * @param _tokenId ID of the token to escrow. */ function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.safeTransferFrom(_owner, this, _tokenId); } /** * @dev Transfers an NFT owned by this contract to another address safely. * @param _receiver The receiving address of NFT. * @param _tokenId ID of the token to transfer. */ function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.safeTransferFrom(this, _receiver, _tokenId); } /** * @dev Adds an auction to the list of open auctions. * @param _tokenId ID of the token to be put on auction. * @param _auction Auction information of this token to open. */ function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.price) ); } /// @dev Cancels the auction which the _seller wants. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCanceled(_tokenId); } /** * @dev Computes the price and sends it to the seller. * Note that this does NOT transfer the ownership of the token. */ function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Gets a reference of the token from auction storage. Auction storage auction = tokenIdToAuction[_tokenId]; // Checks that this auction is currently open require(_isOnAuction(auction)); // Checks that the bid is greater than or equal to the current token price. uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Gets a reference of the seller before the auction gets deleted. address seller = auction.seller; // Removes the auction before sending the proceeds to the sender _removeAuction(_tokenId); // Transfers proceeds to the seller. if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price.sub(auctioneerCut); seller.transfer(sellerProceeds); } // Computes the excess funds included with the bid and transfers it back to bidder. uint256 bidExcess = _bidAmount - price; // Returns the exceeded funds. msg.sender.transfer(bidExcess); // Emits the AuctionSuccessful event. emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /** * @dev Removes an auction from the list of open auctions. * @param _tokenId ID of the NFT on auction to be removed. */ function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /** * @dev Returns true if the NFT is on auction. * @param _auction An auction to check if it exists. */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns the current price of an NFT on auction. function _currentPrice(Auction storage _auction) internal view returns (uint256) { return _auction.price; } /** * @dev Computes the owner's receiving amount from the sale. * @param _price Sale price of the NFT. */ function _computeCut(uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Auction for NFT. * @author VREX Lab Co., Ltd */ contract Auction is Pausable, AuctionBase { /** * @dev Removes all Ether from the contract to the NFT contract. */ function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } /** * @dev Creates and begins a new auction. * @param _tokenId ID of the token to creat an auction, caller must be it's owner. * @param _price Price of the token (in wei). * @param _seller Seller of this token. */ function createAuction( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused canBeStoredWith128Bits(_price) { require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_price), 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) external payable whenNotPaused { _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /** * @dev Cancels an auction and returns the NFT to the current owner. * @param _tokenId ID of the token on auction to cancel. * @param _seller The seller's address. */ function cancelAuction(uint256 _tokenId, address _seller) external { // Requires that this function should only be called from the // `cancelSaleAuction()` of NFT ownership contract. This function gets // the _seller directly from it's arguments, so if this check doesn't // exist, then anyone can cancel the auction! OMG! require(msg.sender == address(nonFungibleContract)); Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(_seller == 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. * @param _tokenId ID of the token on auction to cancel. */ function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /** * @dev Returns the auction information for an NFT * @param _tokenId ID of the NFT on auction */ function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.price, auction.startedAt ); } /** * @dev Returns the current price of the token on auction. * @param _tokenId ID of the token */ function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /** * @title Auction for synthesizing * @author VREX Lab Co., Ltd * @notice Reset fallback function to prevent accidental fund sending to this contract. */ contract SynthesizingAuction is Auction { /** * @dev Sanity check that allows us to ensure that we are pointing to the * right auction in our `setSynthesizingAuctionAddress()` call. */ bool public isSynthesizingAuction = true; /** * @dev Creates a reference to the NFT ownership contract and checks the owner cut is valid * @param _nftAddress Address of a deployed NFT interface contract * @param _cut Percent cut which the owner takes on each auction, between 0-10,000. */ constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721Basic candidateContract = ERC721Basic(_nftAddress); nonFungibleContract = candidateContract; } /** * @dev Creates and begins a new auction. Since this function is wrapped, * requires the caller to be KydyCore contract. * @param _tokenId ID of token to auction, sender must be it's owner. * @param _price Price of the token (in wei). * @param _seller Seller of this token. */ function createAuction( uint256 _tokenId, uint256 _price, address _seller ) external canBeStoredWith128Bits(_price) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_price), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Places a bid for synthesizing. Requires the caller * is the KydyCore contract because all bid functions * should be wrapped. Also returns the Kydy to the * seller rather than the bidder. */ function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid() checks that the token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // Transfers the Kydy back to the seller, and the bidder will get // the baby Kydy. _transfer(seller, _tokenId); } } /** * @title Auction for sale of Kydys. * @author VREX Lab Co., Ltd */ contract SaleAuction is Auction { /** * @dev To make sure we are addressing to the right auction. */ bool public isSaleAuction = true; // Last 5 sale price of Generation 0 Kydys. uint256[5] public lastGen0SalePrices; // Total number of Generation 0 Kydys sold. uint256 public gen0SaleCount; /** * @dev Creates a reference to the NFT ownership contract and checks the owner cut is valid * @param _nftAddress Address of a deployed NFT interface contract * @param _cut Percent cut which the owner takes on each auction, between 0-10,000. */ constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721Basic candidateContract = ERC721Basic(_nftAddress); nonFungibleContract = candidateContract; } /** * @dev Creates and begins a new auction. * @param _tokenId ID of token to auction, sender must be it's owner. * @param _price Price of the token (in wei). * @param _seller Seller of this token. */ function createAuction( uint256 _tokenId, uint256 _price, address _seller ) external canBeStoredWith128Bits(_price) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_price), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Updates lastSalePrice only if the seller is nonFungibleContract. */ function bid(uint256 _tokenId) external payable { // _bid verifies token ID address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If the last sale was not Generation 0 Kydy's, the lastSalePrice doesn't change. if (seller == address(nonFungibleContract)) { // Tracks gen0's latest sale prices. lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } /// @dev Gives the new average Generation 0 sale price after each Generation 0 Kydy sale. function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum = sum.add(lastGen0SalePrices[i]); } return sum / 5; } } /** * @title This contract defines how sales and synthesis auctions for Kydys are created. * @author VREX Lab Co., Ltd */ contract KydyAuction is KydySynthesis { /** * @dev The address of the Auction contract which handles ALL sales of Kydys, both user-generated and Generation 0. */ SaleAuction public saleAuction; /** * @dev The address of another Auction contract which handles synthesis auctions. */ SynthesizingAuction public synthesizingAuction; /** * @dev Sets the address for the sales auction. Only CEO may call this function. * @param _address The address of the sale contract. */ function setSaleAuctionAddress(address _address) external onlyCEO { SaleAuction candidateContract = SaleAuction(_address); // Verifies that the contract is correct require(candidateContract.isSaleAuction()); // Sets the new sale auction contract address. saleAuction = candidateContract; } /** * @dev Sets the address to the synthesis auction. Only CEO may call this function. * @param _address The address of the synthesis contract. */ function setSynthesizingAuctionAddress(address _address) external onlyCEO { SynthesizingAuction candidateContract = SynthesizingAuction(_address); require(candidateContract.isSynthesizingAuction()); synthesizingAuction = candidateContract; } /** * @dev Creates a Kydy sale. */ function createSaleAuction( uint256 _kydyId, uint256 _price ) external whenNotPaused { require(_owns(msg.sender, _kydyId)); require(!isCreating(_kydyId)); _approve(_kydyId, saleAuction); saleAuction.createAuction( _kydyId, _price, msg.sender ); } /** * @dev Creates a synthesis auction. */ function createSynthesizingAuction( uint256 _kydyId, uint256 _price ) external whenNotPaused { require(_owns(msg.sender, _kydyId)); require(isReadyToSynthesize(_kydyId)); _approve(_kydyId, synthesizingAuction); synthesizingAuction.createAuction( _kydyId, _price, msg.sender ); } /** * @dev After bidding for a synthesis auction is accepted, this starts the actual synthesis process. * @param _yangId ID of the yang Kydy on the synthesis auction. * @param _yinId ID of the yin Kydy owned by the bidder. */ function bidOnSynthesizingAuction( uint256 _yangId, uint256 _yinId ) external payable whenNotPaused { require(_owns(msg.sender, _yinId)); require(isReadyToSynthesize(_yinId)); require(_canSynthesizeWithViaAuction(_yinId, _yangId)); uint256 currentPrice = synthesizingAuction.getCurrentPrice(_yangId); require (msg.value >= currentPrice + autoCreationFee); synthesizingAuction.bid.value(msg.value - autoCreationFee)(_yangId); _synthesizeWith(uint32(_yinId), uint32(_yangId)); } /** * @dev Cancels a sale and returns the Kydy back to the owner. * @param _kydyId ID of the Kydy on sale that the owner wishes to cancel. */ function cancelSaleAuction( uint256 _kydyId ) external whenNotPaused { // Checks if the Kydy is in auction. require(_owns(saleAuction, _kydyId)); // Gets the seller of the Kydy. (address seller,,) = saleAuction.getAuction(_kydyId); // Checks that the caller is the real seller. require(msg.sender == seller); // Cancels the sale auction of this kydy by it's seller's request. saleAuction.cancelAuction(_kydyId, msg.sender); } /** * @dev Cancels an synthesis auction. * @param _kydyId ID of the Kydy on the synthesis auction. */ function cancelSynthesizingAuction( uint256 _kydyId ) external whenNotPaused { require(_owns(synthesizingAuction, _kydyId)); (address seller,,) = synthesizingAuction.getAuction(_kydyId); require(msg.sender == seller); synthesizingAuction.cancelAuction(_kydyId, msg.sender); } /** * @dev Transfers the balance. */ function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); synthesizingAuction.withdrawBalance(); } } /** * @title All functions related to creating Kydys * @author VREX Lab Co., Ltd */ contract KydyMinting is KydyAuction { // Limits of the number of Kydys that COO can create. uint256 public constant promoCreationLimit = 888; uint256 public constant gen0CreationLimit = 8888; uint256 public constant gen0StartingPrice = 10 finney; // Counts the number of Kydys that COO has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /** * @dev Creates promo Kydys, up to a limit. Only COO can call this function. * @param _genes Encoded genes of the Kydy to be created. * @param _owner Future owner of the created Kydys. COO is the default owner. */ function createPromoKydy(uint256 _genes, address _owner) external onlyCOO { address kydyOwner = _owner; if (kydyOwner == address(0)) { kydyOwner = cooAddress; } require(promoCreatedCount < promoCreationLimit); promoCreatedCount++; _createKydy(0, 0, 0, _genes, kydyOwner); } /** * @dev Creates a new gen0 Kydy with the given genes and * creates an sale auction of it. */ function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < gen0CreationLimit); uint256 kydyId = _createKydy(0, 0, 0, _genes, address(this)); _approve(kydyId, saleAuction); saleAuction.createAuction( kydyId, _computeNextGen0Price(), address(this) ); gen0CreatedCount++; } /** * @dev Computes the next gen0 auction price. It will be * the average of the past 5 prices + 50%. */ function _computeNextGen0Price() internal view returns (uint256) { uint256 averagePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure not to overflow arithmetic. require(averagePrice == uint256(uint128(averagePrice))); uint256 nextPrice = averagePrice.add(averagePrice / 2); // New gen0 auction price will not be less than the // starting price always. if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } } contract KydyTravelInterface { function balanceOfUnclaimedTT(address _user) public view returns(uint256); function transferTTProduction(address _from, address _to, uint256 _kydyId) public; function getProductionOf(address _user) public view returns (uint256); } /** * @title The Dyverse : A decentralized universe of Kydys, the unique 3D characters and avatars on the Blockchain. * @author VREX Lab Co., Ltd * @dev This is the main KydyCore contract. It keeps track of the kydys over the blockchain, and manages * general operation of the contracts, metadata and important addresses, including defining who can withdraw * the balance from the contract. */ contract KydyCore is KydyMinting { // This is the main Kydy contract. To keep the code upgradable and secure, we broke up the code in two different ways. // First, we separated auction and gene combination functions into several sibling contracts. This allows us to securely // fix bugs and upgrade contracts, if necessary. Please note that while we try to make most code open source, // some code regarding gene combination is not open-source to make it more intriguing for users. // However, as always, advanced users will be able to figure out how it works. // // We also break the core function into a few files, having one contract for each of the major functionalities of the Dyverse. // The breakdown is as follows: // // - KydyBase: This contract defines the most fundamental core functionalities, including data storage and management. // // - KydyAccessControl: This contract manages the roles, addresses and constraints for CEO, CFO and COO. // // - KydyOwnership: This contract provides the methods required for basic non-fungible token transactions. // // - KydySynthesis: This contract contains how new baby Kydy is created via a process called the Synthesis. // // - KydyAuction: This contract manages auction creation and bidding. // // - KydyMinting: This contract defines how we create new Generation 0 Kydys. There is a limit of 8,888 Gen 0 Kydys. // Upgraded version of the core contract. // Should be used when the core contract is broken and an upgrade is required. address public newContractAddress; /// @notice Creates the main Kydy smart contract instance. constructor() public { // Starts with the contract is paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // Starts with the Kydy ID 0 which is invalid one. // So we don't have generation-0 parent issues. _createKydy(0, 0, 0, uint256(-1), address(0)); } /** * @dev Used to mark the smart contract as upgraded when an upgrade happens. * @param _v2Address Upgraded version of the core contract. */ function setNewAddress(address _v2Address) external onlyCEO whenPaused { // We'll announce if the upgrade is needed. newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /** * @dev Rejects all Ether being sent from unregistered addresses, so that users don't accidentally end us Ether. */ function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(synthesizingAuction) ); } /** * @notice Returns all info about a given Kydy. * @param _id ID of the Kydy you are enquiring about. */ function getKydy(uint256 _id) external view returns ( bool isCreating, bool isReady, uint256 rechargeIndex, uint256 nextActionAt, uint256 synthesizingWithId, uint256 createdTime, uint256 yinId, uint256 yangId, uint256 generation, uint256 genes ) { Kydy storage kyd = kydys[_id]; // If this is setted to 0 then it's not at creating mode. isCreating = (kyd.synthesizingWithId != 0); isReady = (kyd.rechargeEndBlock <= block.number); rechargeIndex = uint256(kyd.rechargeIndex); nextActionAt = uint256(kyd.rechargeEndBlock); synthesizingWithId = uint256(kyd.synthesizingWithId); createdTime = uint256(kyd.createdTime); yinId = uint256(kyd.yinId); yangId = uint256(kyd.yangId); generation = uint256(kyd.generation); genes = kyd.genes; } /** * @dev Overrides unpause() to make sure that all external contract addresses are set before unpause. * @notice This should be public rather than external. */ function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(synthesizingAuction != address(0)); require(geneSynthesis != address(0)); require(newContractAddress == address(0)); // Now the contract actually unpauses. super.unpause(); } /// @dev CFO can withdraw the balance available from the contract. function withdrawBalance() external onlyCFO { uint256 balance = address(this).balance; // Subtracts all creation fees needed to be given to the bringKydyHome() callers, // and plus 1 of margin. uint256 subtractFees = (creatingKydys + 1) * autoCreationFee; if (balance > subtractFees) { cfoAddress.transfer(balance - subtractFees); } } /// @dev Sets new tokenURI API for token metadata. function setNewTokenURI(string _newTokenURI) external onlyCLevel { tokenURIBase = _newTokenURI; } // An address of Kydy Travel Plugin. KydyTravelInterface public travelCore; /** * @dev Adds the Kydy Travel Plugin contract to the Kydy Core contract. * @notice We have a plan to add some fun features to the Dyverse. * Your Kydy will travel all over our world while you carry on with your life. * During their travel, they will earn some valuable coins which will then be given to you. * Please stay tuned! */ function setTravelCore(address _newTravelCore) external onlyCEO whenPaused { travelCore = KydyTravelInterface(_newTravelCore); } }
Internal function to mint a new Kydy. _to The address that owns the newly minted Kydy _tokenId uint256 ID of the newly minted Kydy/
function _mint(address _to, uint256 _tokenId) internal { require(!_exists(_tokenId)); _addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); }
6,414,149
/** * MIT License * * Copyright (c) 2019 eToroX Labs * * 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. */ pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./Pausable.sol"; import "../ERC20/ERC20.sol"; import "./AccesslistGuarded.sol"; import "./Accesslist.sol"; import "./roles/BurnerRole.sol"; import "./roles/MinterRole.sol"; import "./RestrictedMinter.sol"; import "./../UpgradeSupport.sol"; /** * @title EToken access guards * @dev This contract implements access guards for functions comprising * the EToken public API. Since these functions may be called through * a proxy, access checks does not rely on the implicit value of * msg.sender but rather on the originSender parameter which is passed * to the functions of this contract. The value of originSender is * captured from msg.sender at the initial landing-point of the * request. */ contract ETokenGuarded is Pausable, ERC20, UpgradeSupport, AccesslistGuarded, BurnerRole, MinterRole, RestrictedMinter { modifier requireOwner(address addr) { require(owner() == addr, "is not owner"); _; } /** * @dev Constructor * @param name The ERC20 detailed token name * @param symbol The ERC20 detailed symbol name * @param decimals Determines the number of decimals of this token * @param accesslist Address of a deployed whitelist contract * @param whitelistEnabled Create token with whitelist enabled * @param externalStorage The external storage contract. * Should be zero address if shouldCreateStorage is true. * @param initialDeployment Defines whether it should * create a new external storage. Should be false if * externalERC20Storage is defined. */ constructor( string name, string symbol, uint8 decimals, Accesslist accesslist, bool whitelistEnabled, Storage externalStorage, address initialMintingRecipient, bool initialDeployment ) internal ERC20(name, symbol, decimals, externalStorage, initialDeployment) AccesslistGuarded(accesslist, whitelistEnabled) RestrictedMinter(initialMintingRecipient) { } /** * @dev Permission enforcing wrapper around the functionality of * EToken.name. Also see the general documentation for this * contract. */ function nameGuarded(address originSender) internal view returns(string) { // Silence warnings originSender; return _name(); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.symbol. Also see the general documentation for this * contract. */ function symbolGuarded(address originSender) internal view returns(string) { // Silence warnings originSender; return _symbol(); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.decimals. Also see the general documentation for this * contract. */ function decimalsGuarded(address originSender) internal view returns(uint8) { // Silence warnings originSender; return _decimals(); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.totalSupply. Also see the general documentation for this * contract. */ function totalSupplyGuarded(address originSender) internal view isEnabled returns(uint256) { // Silence warnings originSender; return _totalSupply(); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.balanceOf. Also see the general documentation for this * contract. */ function balanceOfGuarded(address originSender, address who) internal view isEnabled returns(uint256) { // Silence warnings originSender; return _balanceOf(who); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.allowance. Also see the general documentation for this * contract. */ function allowanceGuarded( address originSender, address owner, address spender ) internal view isEnabled returns(uint256) { // Silence warnings originSender; return _allowance(owner, spender); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.transfer. Also see the general documentation for this * contract. */ function transferGuarded(address originSender, address to, uint256 value) internal isEnabled whenNotPaused requireHasAccess(to) requireHasAccess(originSender) returns (bool) { _transfer(originSender, to, value); return true; } /** * @dev Permission enforcing wrapper around the functionality of * EToken.approve. Also see the general documentation for this * contract. */ function approveGuarded( address originSender, address spender, uint256 value ) internal isEnabled whenNotPaused requireHasAccess(spender) requireHasAccess(originSender) returns (bool) { _approve(originSender, spender, value); return true; } /** * @dev Permission enforcing wrapper around the functionality of * EToken.transferFrom. Also see the documentation for this * contract. */ function transferFromGuarded( address originSender, address from, address to, uint256 value ) internal isEnabled whenNotPaused requireHasAccess(originSender) requireHasAccess(from) requireHasAccess(to) returns (bool) { _transferFrom( originSender, from, to, value ); return true; } /** * @dev Permission enforcing wrapper around the functionality of * EToken.increaseAllowance, Also see the general documentation * for this contract. */ function increaseAllowanceGuarded( address originSender, address spender, uint256 addedValue ) internal isEnabled whenNotPaused requireHasAccess(originSender) requireHasAccess(spender) returns (bool) { _increaseAllowance(originSender, spender, addedValue); return true; } /** * @dev Permission enforcing wrapper around the functionality of * EToken.decreaseAllowance. Also see the general documentation * for this contract. */ function decreaseAllowanceGuarded( address originSender, address spender, uint256 subtractedValue ) internal isEnabled whenNotPaused requireHasAccess(originSender) requireHasAccess(spender) returns (bool) { _decreaseAllowance(originSender, spender, subtractedValue); return true; } /** * @dev Permission enforcing wrapper around the functionality of * EToken.burn. Also see the general documentation for this * contract. */ function burnGuarded(address originSender, uint256 value) internal isEnabled requireBurner(originSender) { _burn(originSender, value); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.burnFrom. Also see the general documentation for this * contract. */ function burnFromGuarded(address originSender, address from, uint256 value) internal isEnabled requireBurner(originSender) { _burnFrom(originSender, from, value); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.mint. Also see the general documentation for this * contract. */ function mintGuarded(address originSender, address to, uint256 value) internal isEnabled requireMinter(originSender) requireMintingRecipient(to) returns (bool success) { // Silence warnings originSender; _mint(to, value); return true; } /** * @dev Permission enforcing wrapper around the functionality of * EToken.changeMintingRecipient. Also see the general * documentation for this contract. */ function changeMintingRecipientGuarded( address originSender, address mintingRecip ) internal isEnabled requireOwner(originSender) { _changeMintingRecipient(originSender, mintingRecip); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.pause. Also see the general documentation for this * contract. */ function pauseGuarded(address originSender) internal isEnabled requireIsPauser(originSender) whenNotPaused { _pause(originSender); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.unpause. Also see the general documentation for this * contract. */ function unpauseGuarded(address originSender) internal isEnabled requireIsPauser(originSender) whenPaused { _unpause(originSender); } /** * @dev Permission enforcing wrapper around the functionality of * EToken.paused. Also see the general documentation for this * contract. */ function pausedGuarded(address originSender) internal view isEnabled returns (bool) { // Silence warnings originSender; return _paused(); } }
Permission enforcing wrapper around the functionality of EToken.burnFrom. Also see the general documentation for this contract./
function burnFromGuarded(address originSender, address from, uint256 value) internal isEnabled requireBurner(originSender) { _burnFrom(originSender, from, value); }
13,096,760
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); } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0-only /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INBUNIERC20 { /** * @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); event Log(string log); } library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: 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, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Encore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract EncoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeMath for uint; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of ENCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accEncorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accEncorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. ENCOREs to distribute per block. uint256 accEncorePerShare; // Accumulated ENCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? bool depositable; // Is this pool depositable? mapping(address => mapping(address => uint256)) allowance; } // The ENCORE TOKEN! INBUNIERC20 public encore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; address public ENCOREETHLPBurnAddress; mapping(address=>bool) public voidWithdrawList; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } 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 ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _encore, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 1666; encore = _encore; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable, bool _depositable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accEncorePerShare: 0, withdrawable : _withdrawable, depositable : _depositable }) ); } // Update the given pool's ENCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } function setPoolDepositable( uint256 _pid, bool _depositable ) public onlyOwner { poolInfo[_pid].depositable = _depositable; } // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus uint16 public DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 2000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } function editVoidWithdrawList(address _user, bool _voidfee) public onlyOwner { voidWithdrawList[_user] = _voidfee; } // ---- // Function that adds pending rewards, called by the ENCORE token. // ---- uint256 private encoreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = encore.balanceOf(address(this)).sub(encoreBalance); if(newRewards > 0) { encoreBalance = encore.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public returns (uint256 encoreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } encoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 encoreRewardFee = encoreRewardWhole.mul(DEV_FEE).div(10000); uint256 encoreRewardToDistribute = encoreRewardWhole.sub(encoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(encoreRewardFee); pool.accEncorePerShare = pool.accEncorePerShare.add( encoreRewardToDistribute.mul(1e12).div(tokenSupply) ); } function safeFixUnits(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); } // Deposit tokens to EncoreVault for ENCORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.depositable == true, "Depositing into this pool is disabled"); massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.transferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); require(pool.depositable == true, "Depositing into this pool is disabled"); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.transferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } function setENCOREETHLPBurnAddress(address _burn) public onlyOwner { ENCOREETHLPBurnAddress = _burn; } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from EncoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } function claim(uint256 _pid) public { _withdraw(_pid, 0, msg.sender,msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][from]; massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming ENCORE farmed if(_amount > 0) { require(pool.withdrawable, "Withdrawing from this pool is disabled"); user.amount = user.amount.sub(_amount, "Insufficient balance"); if(_pid == 0) { if(voidWithdrawList[to] || ENCOREETHLPBurnAddress == address(0)) { pool.token.transfer(address(to), _amount); } else { pool.token.transfer(address(to), _amount.mul(95).div(100)); pool.token.transfer(address(ENCOREETHLPBurnAddress), _amount.mul(5).div(100)); } } else { pool.token.transfer(address(to), _amount); } } user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingENCORE(_pid, from); if(pending > 0) { safeEncoreTransfer(from, pending); } } function pendingENCORE(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accEncorePerShare = pool.accEncorePerShare; return user.amount.mul(accEncorePerShare).div(1e12).sub(user.rewardDebt); } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.transfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe encore transfer function, just in case if rounding error causes pool to not have enough ENCOREs. function safeEncoreTransfer(address _to, uint256 _amount) internal { if(_amount == 0) return; uint256 encoreBal = encore.balanceOf(address(this)); encore.transfer(_to, _amount); encoreBalance = encore.balanceOf(address(this)); if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; safeEncoreTransfer(devaddr, devSend); } } function stakedTokens(uint256 _pid, address _user) public view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } // Update dev address by the previous dev. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; }
299,384
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { LS1Types } from '../lib/LS1Types.sol'; /** * @title LS1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract LS1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. LS1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. /// We also restrict other changes which could affect borrowers' repayment plans, such as /// modifications to the epoch schedule, or to borrower allocations. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => LS1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. LS1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => LS1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. Note: The shortfallCounter field is unused. LS1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; /// @dev Information about shortfalls that have occurred. LS1Types.Shortfall[] internal _SHORTFALLS_; // ============ Borrower Accounting ============ /// @dev The units allocated to each borrower. /// @dev Values are represented relative to total allocation, i.e. as hundredeths of a percent. /// Also, the total of the values contained in the mapping must always equal the total /// allocation (i.e. must sum to 10,000). mapping(address => LS1Types.StoredAllocation) internal _BORROWER_ALLOCATIONS_; /// @dev The token balance currently borrowed by the borrower. mapping(address => uint256) internal _BORROWED_BALANCES_; /// @dev The total token balance currently borrowed by borrowers. uint256 internal _TOTAL_BORROWED_BALANCE_; /// @dev Indicates whether a borrower is restricted from new borrowing. mapping(address => bool) internal _BORROWER_RESTRICTIONS_; // ============ Debt Accounting ============ /// @dev The debt balance owed to each staker. mapping(address => uint256) internal _STAKER_DEBT_BALANCES_; /// @dev The debt balance by borrower. mapping(address => uint256) internal _BORROWER_DEBT_BALANCES_; /// @dev The total debt balance of borrowers. uint256 internal _TOTAL_BORROWER_DEBT_BALANCE_; /// @dev The total debt amount repaid and not yet withdrawn. uint256 internal _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title LS1Types * @author dYdX * * @dev Structs used by the LiquidityStaking contract. */ library LS1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters representing a shortfall event. * * @param index Fraction of inactive funds converted into debt, scaled by SHORTFALL_INDEX_BASE. * @param epoch The epoch in which the shortfall occurred. */ struct Shortfall { uint16 epoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint224 index; // Note: Save on contract bytecode size by reusing uint224 instead of uint240. } /** * @dev A balance, possibly with a change scheduled for the next epoch. * Also includes cached index information for inactive balances. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. * @param shortfallCounter Incrementing counter of the next shortfall index to be applied. */ struct StoredBalance { uint16 currentEpoch; // Supports at least 1000 years given min epoch length of 6 days. uint112 currentEpochBalance; uint112 nextEpochBalance; uint16 shortfallCounter; // Only for staker inactive balances. At most one shortfall per epoch. } /** * @dev A borrower allocation, possibly with a change scheduled for the next epoch. */ struct StoredAllocation { uint16 currentEpoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint120 currentEpochAllocation; uint120 nextEpochAllocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract LS1Getters is LS1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The token balance currently borrowed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens borrowed. */ function getBorrowedBalance( address borrower ) external view returns (uint256) { return _BORROWED_BALANCES_[borrower]; } /** * @notice The total token balance borrowed by borrowers. * * @return The number of tokens borrowed. */ function getTotalBorrowedBalance() external view returns (uint256) { return _TOTAL_BORROWED_BALANCE_; } /** * @notice The debt balance owed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens owed. */ function getBorrowerDebtBalance( address borrower ) external view returns (uint256) { return _BORROWER_DEBT_BALANCES_[borrower]; } /** * @notice The total debt balance owed by borrowers. * * @return The number of tokens owed. */ function getTotalBorrowerDebtBalance() external view returns (uint256) { return _TOTAL_BORROWER_DEBT_BALANCE_; } /** * @notice The total debt repaid by borrowers and available for stakers to withdraw. * * @return The number of tokens available. */ function getTotalDebtAvailableToWithdraw() external view returns (uint256) { return _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } /** * @notice Check whether a borrower is restricted from new borrowing. * * @param borrower The borrower to check. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestrictedForBorrower( address borrower ) external view returns (bool) { return _BORROWER_RESTRICTIONS_[borrower]; } /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (LS1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * Other changes which could affect borrowers' repayment plans are also restricted during * this period. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get information about a shortfall that occurred. * * @param shortfallCounter The array index for the shortfall event to look up. * * @return Struct containing the epoch and shortfall index value. */ function getShortfall( uint256 shortfallCounter ) external view returns (LS1Types.Shortfall memory) { return _SHORTFALLS_[shortfallCounter]; } /** * @notice Get the number of shortfalls that have occurred. * * @return The number of shortfalls that have occurred. */ function getShortfallCount() external view returns (uint256) { return _SHORTFALLS_.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: Apache-2.0 // // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { LS1Admin } from './impl/LS1Admin.sol'; import { LS1Borrowing } from './impl/LS1Borrowing.sol'; import { LS1DebtAccounting } from './impl/LS1DebtAccounting.sol'; import { LS1ERC20 } from './impl/LS1ERC20.sol'; import { LS1Failsafe } from './impl/LS1Failsafe.sol'; import { LS1Getters } from './impl/LS1Getters.sol'; import { LS1Operators } from './impl/LS1Operators.sol'; /** * @title LiquidityStakingV1 * @author dYdX * * @notice Contract for staking tokens, which may then be borrowed by pre-approved borrowers. * * NOTE: Most functions will revert if epoch zero has not started. */ contract LiquidityStakingV1 is LS1Borrowing, LS1DebtAccounting, LS1Admin, LS1Operators, LS1Getters, LS1Failsafe { // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Borrowing(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ function initialize( uint256 interval, uint256 offset, uint256 blackoutWindow ) external initializer { __LS1Roles_init(); __LS1EpochSchedule_init(interval, offset, blackoutWindow); __LS1Rewards_init(); __LS1BorrowerAllocations_init(); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Borrowing } from './LS1Borrowing.sol'; /** * @title LS1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract LS1Admin is LS1Borrowing { using SafeCast for uint256; using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * Reverts if the new interval is less than twice the blackout window. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require(block.timestamp < offset, 'LS1Admin: Started epoch zero'); _setEpochParameters(interval, offset); return; } // Require that we are not currently in a blackout window. require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require(originalCurrentEpoch == newCurrentEpoch, 'LS1Admin: Changed epochs'); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBlackoutWindow(blackoutWindow); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } /** * @notice Change the allocations of certain borrowers. Can be used to add and remove borrowers. * Increases take effect in the next epoch, but decreases will restrict borrowing immediately. * This function cannot be called during the blackout window. * * @param borrowers Array of borrower addresses. * @param newAllocations Array of new allocations per borrower, as hundredths of a percent. */ function setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { require(borrowers.length == newAllocations.length, 'LS1Admin: Params length mismatch'); require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBorrowerAllocations(borrowers, newAllocations); } function setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { _setBorrowingRestriction(borrower, isBorrowingRestricted); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Borrowing * @author dYdX * * @dev External functions for borrowers. See LS1BorrowerAllocations for details on * borrower accounting. */ abstract contract LS1Borrowing is LS1Staking, LS1BorrowerAllocations { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Borrowed( address indexed borrower, uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( address indexed borrower, address sender, uint256 amount, uint256 newBorrowedBalance ); event RepaidDebt( address indexed borrower, address sender, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Borrow staked funds. * * @param amount The token amount to borrow. */ function borrow( uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot borrow zero'); address borrower = msg.sender; // Revert if the borrower is restricted. require(!_BORROWER_RESTRICTIONS_[borrower], 'LS1Borrowing: Restricted'); // Get contract available amount and revert if there is not enough to withdraw. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); require( amount <= totalAvailableForBorrow, 'LS1Borrowing: Amount > available' ); // Get new net borrow and revert if it is greater than the allocated balance for new borrowing. uint256 newBorrowedBalance = _BORROWED_BALANCES_[borrower].add(amount); require( newBorrowedBalance <= _getAllocatedBalanceForNewBorrowing(borrower), 'LS1Borrowing: Amount > allocated' ); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.add(amount); // Transfer token to the borrower. STAKED_TOKEN.safeTransfer(borrower, amount); emit Borrowed(borrower, amount, newBorrowedBalance); } /** * @notice Repay borrowed funds for the specified borrower. Reverts if repay amount exceeds * borrowed amount. * * @param borrower The borrower on whose behalf to make a repayment. * @param amount The amount to repay. */ function repayBorrow( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; require(amount <= oldBorrowedBalance, 'LS1Borrowing: Repay > borrowed'); uint256 newBorrowedBalance = oldBorrowedBalance.sub(amount); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidBorrow(borrower, msg.sender, amount, newBorrowedBalance); } /** * @notice Repay a debt amount owed by a borrower. * * @param borrower The borrower whose debt to repay. * @param amount The amount to repay. */ function repayDebt( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldDebtAmount = _BORROWER_DEBT_BALANCES_[borrower]; require(amount <= oldDebtAmount, 'LS1Borrowing: Repay > debt'); uint256 newDebtBalance = oldDebtAmount.sub(amount); // Update storage. _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_.add(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidDebt(borrower, msg.sender, amount, newDebtBalance); } /** * @notice Get the max additional amount that the borrower can borrow. * * @return The max additional amount that the borrower can borrow right now. */ function getBorrowableAmount( address borrower ) external view returns (uint256) { if (_BORROWER_RESTRICTIONS_[borrower]) { return 0; } // Get the remaining unused allocation for the borrower. uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; uint256 borrowerAllocatedBalance = _getAllocatedBalanceForNewBorrowing(borrower); if (borrowerAllocatedBalance <= oldBorrowedBalance) { return 0; } uint256 borrowerRemainingAllocatedBalance = borrowerAllocatedBalance.sub(oldBorrowedBalance); // Don't allow new borrowing to take out funds that are reserved for debt or inactive balances. // Typically, this will not be the limiting factor, but it can be. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); return Math.min(borrowerRemainingAllocatedBalance, totalAvailableForBorrow); } // ============ Public Functions ============ /** * @notice Get the funds currently available in the contract for borrowing. * * @return The amount of non-debt, non-inactive funds in the contract. */ function getContractBalanceAvailableToBorrow() public view returns (uint256) { uint256 availableStake = getContractBalanceAvailableToWithdraw(); uint256 inactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Note: The funds available to withdraw may be less than the inactive balance. if (availableStake <= inactiveBalance) { return 0; } return availableStake.sub(inactiveBalance); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; /** * @title LS1DebtAccounting * @author dYdX * * @dev Allows converting an overdue balance into "debt", which is accounted for separately from * the staked and borrowed balances. This allows the system to rebalance/restabilize itself in the * case where a borrower fails to return borrowed funds on time. * * The shortfall debt calculation is as follows: * * - Let A be the total active balance. * - Let B be the total borrowed balance. * - Let X be the total inactive balance. * - Then, a shortfall occurs if at any point B > A. * - The shortfall debt amount is `D = B - A` * - The borrowed balances are decreased by `B_new = B - D` * - The inactive balances are decreased by `X_new = X - D` * - The shortfall index is recorded as `Y = X_new / X` * - The borrower and staker debt balances are increased by `D` * * Note that `A + X >= B` (The active and inactive balances are at least the borrowed balance.) * This implies that `X >= D` (The inactive balance is always at least the shortfall debt.) */ abstract contract LS1DebtAccounting is LS1BorrowerAllocations { using SafeERC20 for IERC20; using SafeMath for uint256; using Math for uint256; // ============ Events ============ event ConvertedInactiveBalancesToDebt( uint256 shortfallAmount, uint256 shortfallIndex, uint256 newInactiveBalance ); event DebtMarked( address indexed borrower, uint256 amount, uint256 newBorrowedBalance, uint256 newDebtBalance ); // ============ External Functions ============ /** * @notice Restrict a borrower from borrowing. The borrower must have exceeded their borrowing * allocation. Can be called by anyone. * * Unlike markDebt(), this function can be called even if the contract in TOTAL is not insolvent. */ function restrictBorrower( address borrower ) external nonReentrant { require( isBorrowerOverdue(borrower), 'LS1DebtAccounting: Borrower not overdue' ); _setBorrowingRestriction(borrower, true); } /** * @notice Convert the shortfall amount between the active and borrowed balances into “debt.” * * The function determines the size of the debt, and then does the following: * - Assign the debt to borrowers, taking the same amount out of their borrowed balance. * - Impose borrow restrictions on borrowers to whom the debt was assigned. * - Socialize the loss pro-rata across inactive balances. Each balance with a loss receives * an equal amount of debt balance that can be withdrawn as debts are repaid. * * @param borrowers A list of borrowers who are responsible for the full shortfall amount. * * @return The shortfall debt amount. */ function markDebt( address[] calldata borrowers ) external nonReentrant returns (uint256) { // The debt is equal to the difference between the total active and total borrowed balances. uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent); // Attribute debt to borrowers. _attributeDebtToBorrowers(shortfallDebt, totalActiveCurrent, borrowers); // Apply the debt to inactive balances, moving the same amount into users debt balances. _convertInactiveBalanceToDebt(shortfallDebt); return shortfallDebt; } // ============ Public Functions ============ /** * @notice Whether the borrower is overdue on a payment, and is currently subject to having their * borrowing rights revoked. * * @param borrower The borrower to check. */ function isBorrowerOverdue( address borrower ) public view returns (bool) { uint256 allocatedBalance = getAllocatedBalanceCurrentEpoch(borrower); uint256 borrowedBalance = _BORROWED_BALANCES_[borrower]; return borrowedBalance > allocatedBalance; } // ============ Private Functions ============ /** * @dev Helper function to partially or fully convert inactive balances to debt. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. */ function _convertInactiveBalanceToDebt( uint256 shortfallDebt ) private { // Get the total inactive balance. uint256 oldInactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Calculate the index factor for the shortfall. uint256 newInactiveBalance = 0; uint256 shortfallIndex = 0; if (oldInactiveBalance > shortfallDebt) { newInactiveBalance = oldInactiveBalance.sub(shortfallDebt); shortfallIndex = SHORTFALL_INDEX_BASE.mul(newInactiveBalance).div(oldInactiveBalance); } // Get the shortfall amount applied to inactive balances. uint256 shortfallAmount = oldInactiveBalance.sub(newInactiveBalance); // Apply the loss. This moves the debt from stakers' inactive balances to their debt balances. _applyShortfall(shortfallAmount, shortfallIndex); emit ConvertedInactiveBalancesToDebt(shortfallAmount, shortfallIndex, newInactiveBalance); } /** * @dev Helper function to attribute debt to borrowers, adding it to their debt balances. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. * @param totalActiveCurrent The total active balance for the current epoch. * @param borrowers A list of borrowers responsible for the full shortfall amount. */ function _attributeDebtToBorrowers( uint256 shortfallDebt, uint256 totalActiveCurrent, address[] calldata borrowers ) private { // Find borrowers to attribute the total debt amount to. The sum of all borrower shortfalls is // always at least equal to the overall shortfall, so it is always possible to specify a list // of borrowers whose excess borrows cover the full shortfall amount. // // Denominate values in “points” scaled by TOTAL_ALLOCATION to avoid rounding. uint256 debtToBeAttributedPoints = shortfallDebt.mul(TOTAL_ALLOCATION); uint256 shortfallDebtAfterRounding = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 borrowedBalanceTokenAmount = _BORROWED_BALANCES_[borrower]; uint256 borrowedBalancePoints = borrowedBalanceTokenAmount.mul(TOTAL_ALLOCATION); uint256 allocationPoints = getAllocationFractionCurrentEpoch(borrower); uint256 allocatedBalancePoints = totalActiveCurrent.mul(allocationPoints); // Skip this borrower if they have not exceeded their allocation. if (borrowedBalancePoints <= allocatedBalancePoints) { continue; } // Calculate the borrower's debt, and limit to the remaining amount to be allocated. uint256 borrowerDebtPoints = borrowedBalancePoints.sub(allocatedBalancePoints); borrowerDebtPoints = Math.min(borrowerDebtPoints, debtToBeAttributedPoints); // Move the debt from the borrowers' borrowed balance to the debt balance. Rounding may occur // when converting from “points” to tokens. We round up to ensure the final borrowed balance // is not greater than the allocated balance. uint256 borrowerDebtTokenAmount = borrowerDebtPoints.divRoundUp(TOTAL_ALLOCATION); uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].add(borrowerDebtTokenAmount); uint256 newBorrowedBalance = borrowedBalanceTokenAmount.sub(borrowerDebtTokenAmount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _BORROWED_BALANCES_[borrower] = newBorrowedBalance; emit DebtMarked(borrower, borrowerDebtTokenAmount, newBorrowedBalance, newDebtBalance); shortfallDebtAfterRounding = shortfallDebtAfterRounding.add(borrowerDebtTokenAmount); // Restrict the borrower from further borrowing. _setBorrowingRestriction(borrower, true); // Update the remaining amount to allocate. debtToBeAttributedPoints = debtToBeAttributedPoints.sub(borrowerDebtPoints); // Exit early if all debt was allocated. if (debtToBeAttributedPoints == 0) { break; } } // Require the borrowers to cover the full debt amount. This should always be possible. require( debtToBeAttributedPoints == 0, 'LS1DebtAccounting: Borrowers do not cover the shortfall' ); // Move the debt from the total borrowed balance to the total debt balance. _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(shortfallDebtAfterRounding); _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.add(shortfallDebtAfterRounding); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Allows a user with an active stake to transfer their * staked tokens to another user, even if they would otherwise be restricted from withdrawing. */ abstract contract LS1ERC20 is LS1StakedBalances, IERC20Detailed { using SafeMath for uint256; // ============ External Functions ============ function name() external pure override returns (string memory) { return 'dYdX Staked USDC'; } function symbol() external pure override returns (string memory) { return 'stkUSDC'; } function decimals() external pure override returns (uint8) { return 6; } /** * @notice Get the total supply of `STAKED_TOKEN` staked to the contract. * This value is calculated from adding the active + inactive balances of * this current epoch. * * @return The total staked balance of this contract. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get the current balance of `STAKED_TOKEN` the user has staked to the contract. * This value includes the users active + inactive balances, but note that only * their active balance in the next epoch is transferable. * * @param account The account to get the balance of. * * @return The user's balance. */ function balanceOf( address account ) external view override returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'LS1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'LS1ERC20: Decreased allowance below zero' ) ); return true; } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'LS1ERC20: Transfer from address(0)'); require(recipient != address(0), 'LS1ERC20: Transfer to address(0)'); require( getTransferableBalance(sender) >= amount, 'LS1ERC20: Transfer exceeds next epoch active balance' ); _transferCurrentAndNextActiveBalance(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'LS1ERC20: Approve from address(0)'); require(spender != address(0), 'LS1ERC20: Approve to address(0)'); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Failsafe * @author dYdX * * @dev Functions for recovering from very unlikely edge cases. */ abstract contract LS1Failsafe is LS1StakedBalances { using SafeCast for uint256; using SafeMath for uint256; /** * @notice Settle the sender's inactive balance up to the specified epoch. This allows the * balance to be settled while putting an upper bound on the gas expenditure per function call. * This is unlikely to be needed in practice. * * @param maxEpoch The epoch to settle the sender's inactive balance up to. */ function failsafeSettleUserInactiveBalanceToEpoch( uint256 maxEpoch ) external nonReentrant { address staker = msg.sender; _failsafeSettleUserInactiveBalance(staker, maxEpoch); } /** * @notice Sets the sender's inactive balance to zero. This allows for recovery from a situation * where the gas cost to settle the balance is higher than the value of the balance itself. * We provide this function as an alternative to settlement, since the gas cost for settling an * inactive balance is unbounded (except in that it may grow at most linearly with the number of * epochs that have passed). */ function failsafeDeleteUserInactiveBalance() external nonReentrant { address staker = msg.sender; _failsafeDeleteUserInactiveBalance(staker); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are three types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. * * DEBT_OPERATOR_ROLE: * * This operator is allowed to decrease staker and borrower debt balances. Typically, each change * to a staker debt balance should be offset by a corresponding change in a borrower debt * balance, but this is not strictly required. This role could used by a smart contract to * tokenize debt balances or to provide a pro-rata distribution to debt holders, for example. */ abstract contract LS1Operators is LS1Staking { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); event OperatorDecreasedStakerDebt( address indexed staker, uint256 amount, uint256 newDebtBalance, address operator ); event OperatorDecreasedBorrowerDebt( address indexed borrower, uint256 amount, uint256 newDebtBalance, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, amount); emit OperatorWithdrawalRequestedFor(staker, amount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, amount); emit OperatorWithdrewStakeFor(staker, recipient, amount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } /** * @notice Decreased the balance recording debt owed to a staker. * * @param staker The staker whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseStakerDebt( address staker, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 oldDebtBalance = _settleStakerDebtBalance(staker); uint256 newDebtBalance = oldDebtBalance.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit OperatorDecreasedStakerDebt(staker, amount, newDebtBalance, msg.sender); return newDebtBalance; } /** * @notice Decreased the balance recording debt owed by a borrower. * * @param borrower The borrower whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseBorrowerDebt( address borrower, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].sub(amount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); emit OperatorDecreasedBorrowerDebt(borrower, amount, newDebtBalance, msg.sender); return newDebtBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title SafeCast * @author dYdX * * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require(uint256(b) == a, 'SafeCast: toUint16 overflow'); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require(uint256(b) == a, 'SafeCast: toUint32 overflow'); return b; } /** * @dev Downcast to a uint112, reverting on overflow. */ function toUint112( uint256 a ) internal pure returns (uint112) { uint112 b = uint112(a); require(uint256(b) == a, 'SafeCast: toUint112 overflow'); return b; } /** * @dev Downcast to a uint120, reverting on overflow. */ function toUint120( uint256 a ) internal pure returns (uint120) { uint120 b = uint120(a); require(uint256(b) == a, 'SafeCast: toUint120 overflow'); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require(uint256(b) == a, 'SafeCast: toUint224 overflow'); return b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1BorrowerAllocations * @author dYdX * * @dev Gives a set of addresses permission to withdraw staked funds. * * The amount that can be withdrawn depends on a borrower's allocation percentage and the total * available funds. Both the allocated percentage and total available funds can change, at * predefined times specified by LS1EpochSchedule. * * If a borrower's borrowed balance is greater than their allocation at the start of the next epoch * then they are expected and trusted to return the difference before the start of that epoch. */ abstract contract LS1BorrowerAllocations is LS1StakedBalances { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The total units to be allocated. uint256 public constant TOTAL_ALLOCATION = 1e4; // ============ Events ============ event ScheduledBorrowerAllocationChange( address indexed borrower, uint256 oldAllocation, uint256 newAllocation, uint256 epochNumber ); event BorrowingRestrictionChanged( address indexed borrower, bool isBorrowingRestricted ); // ============ Initializer ============ function __LS1BorrowerAllocations_init() internal { _BORROWER_ALLOCATIONS_[address(0)] = LS1Types.StoredAllocation({ currentEpoch: 0, currentEpochAllocation: TOTAL_ALLOCATION.toUint120(), nextEpochAllocation: TOTAL_ALLOCATION.toUint120() }); } // ============ Public Functions ============ /** * @notice Get the borrower allocation for the current epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's current allocation in hundreds of a percent. */ function getAllocationFractionCurrentEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).currentEpochAllocation); } /** * @notice Get the borrower allocation for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's next allocation in hundreds of a percent. */ function getAllocationFractionNextEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).nextEpochAllocation); } /** * @notice Get the allocated borrowable token balance of a borrower for the current epoch. * * This is the amount which a borrower can be penalized for exceeding. * * @param borrower The borrower to get the allocation for. * * @return The token amount allocated to the borrower for the current epoch. */ function getAllocatedBalanceCurrentEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionCurrentEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceCurrentEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } /** * @notice Preview the allocated balance of a borrower for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The anticipated token amount allocated to the borrower for the next epoch. */ function getAllocatedBalanceNextEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionNextEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceNextEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Internal Functions ============ /** * @dev Change the allocations of certain borrowers. */ function _setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) internal { // These must net out so that the total allocation is unchanged. uint256 oldAllocationSum = 0; uint256 newAllocationSum = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 newAllocation = newAllocations[i]; // Get the old allocation. LS1Types.StoredAllocation memory allocationStruct = _loadBorrowerAllocation(borrower); uint256 oldAllocation = uint256(allocationStruct.currentEpochAllocation); // Update the borrower's next allocation. allocationStruct.nextEpochAllocation = newAllocation.toUint120(); // If epoch zero hasn't started, update current allocation as well. uint256 epochNumber = 0; if (hasEpochZeroStarted()) { epochNumber = uint256(allocationStruct.currentEpoch).add(1); } else { allocationStruct.currentEpochAllocation = newAllocation.toUint120(); } // Commit the new allocation. _BORROWER_ALLOCATIONS_[borrower] = allocationStruct; emit ScheduledBorrowerAllocationChange(borrower, oldAllocation, newAllocation, epochNumber); // Record totals. oldAllocationSum = oldAllocationSum.add(oldAllocation); newAllocationSum = newAllocationSum.add(newAllocation); } // Require the total allocated units to be unchanged. require( oldAllocationSum == newAllocationSum, 'LS1BorrowerAllocations: Invalid' ); } /** * @dev Restrict a borrower from further borrowing. */ function _setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) internal { bool oldIsBorrowingRestricted = _BORROWER_RESTRICTIONS_[borrower]; if (oldIsBorrowingRestricted != isBorrowingRestricted) { _BORROWER_RESTRICTIONS_[borrower] = isBorrowingRestricted; emit BorrowingRestrictionChanged(borrower, isBorrowingRestricted); } } /** * @dev Get the allocated balance that the borrower can make use of for new borrowing. * * @return The amount that the borrower can borrow up to. */ function _getAllocatedBalanceForNewBorrowing( address borrower ) internal view returns (uint256) { // Use the smaller of the current and next allocation fractions, since if a borrower's // allocation was just decreased, we should take that into account in limiting new borrows. uint256 currentAllocation = getAllocationFractionCurrentEpoch(borrower); uint256 nextAllocation = getAllocationFractionNextEpoch(borrower); uint256 allocation = Math.min(currentAllocation, nextAllocation); // If we are in the blackout window, use the next active balance. Otherwise, use current. // Note that the next active balance is never greater than the current active balance. uint256 availableTokens; if (inBlackoutWindow()) { availableTokens = getTotalActiveBalanceNextEpoch(); } else { availableTokens = getTotalActiveBalanceCurrentEpoch(); } return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Private Functions ============ function _loadBorrowerAllocation( address borrower ) private view returns (LS1Types.StoredAllocation memory) { LS1Types.StoredAllocation memory allocation = _BORROWER_ALLOCATIONS_[borrower]; // Ignore rollover logic before epoch zero. if (hasEpochZeroStarted()) { uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(allocation.currentEpoch)) { // Roll the allocation forward. allocation.currentEpoch = currentEpoch.toUint16(); allocation.currentEpochAllocation = allocation.nextEpochAllocation; } } return allocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1ERC20 } from './LS1ERC20.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Staking * @author dYdX * * @dev External functions for stakers. See LS1StakedBalances for details on staker accounting. */ abstract contract LS1Staking is LS1StakedBalances, LS1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 amount ); event WithdrawalRequested( address indexed staker, uint256 amount ); event WithdrewStake( address indexed staker, address recipient, uint256 amount ); event WithdrewDebt( address indexed staker, address recipient, uint256 amount, uint256 newDebtBalance ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param amount The amount to stake. */ function stake( uint256 amount ) external nonReentrant { _stake(msg.sender, amount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param amount The amount to stake. */ function stakeFor( address staker, uint256 amount ) external nonReentrant { _stake(staker, amount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawal( uint256 amount ) external nonReentrant { _requestWithdrawal(msg.sender, amount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 amount ) external nonReentrant { _withdrawStake(msg.sender, recipient, amount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, amount); return amount; } /** * @notice Withdraw a debt amount owed to the sender, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The token amount to withdraw from the sender's debt balance. */ function withdrawDebt( address recipient, uint256 amount ) external nonReentrant { _withdrawDebt(msg.sender, recipient, amount); } /** * @notice Withdraw the max available debt amount. * * This is less gas-efficient than querying the max via eth_call and calling withdrawDebt(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxDebt( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getDebtAvailableToWithdraw(msg.sender); _withdrawDebt(msg.sender, recipient, amount); return amount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available to withdraw taking into account the contract balance. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. uint256 stakerBalance = getInactiveBalanceCurrentEpoch(staker); uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); return Math.min(stakerBalance, totalStakeAvailable); } /** * @notice Get the funds currently available in the contract for staker withdrawals. * * @return The amount of non-debt funds in the contract. */ function getContractBalanceAvailableToWithdraw() public view returns (uint256) { uint256 contractBalance = STAKED_TOKEN.balanceOf(address(this)); uint256 availableDebtBalance = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return contractBalance.sub(availableDebtBalance); // Should never underflow. } /** * @notice Get the amount of debt available to withdraw. * * @param staker The address whose balance to check. * * @return The debt amount that can be withdrawn. */ function getDebtAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that `totalDebtAvailable` should never be less than the contract token balance. uint256 stakerDebtBalance = getStakerDebtBalance(staker); uint256 totalDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return Math.min(stakerDebtBalance, totalDebtAvailable); } // ============ Internal Functions ============ function _stake( address staker, uint256 amount ) internal { // Increase current and next active balance. _increaseCurrentAndNextActiveBalance(staker, amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit Staked(staker, msg.sender, amount); emit Transfer(address(0), msg.sender, amount); } function _requestWithdrawal( address staker, uint256 amount ) internal { require( !inBlackoutWindow(), 'LS1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( amount <= requestableBalance, 'LS1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, amount); emit WithdrawalRequested(staker, amount); } function _withdrawStake( address staker, address recipient, uint256 amount ) internal { // Get contract available amount and revert if there is not enough to withdraw. uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); require( amount <= totalStakeAvailable, 'LS1Staking: Withdraw exceeds amount available in the contract' ); // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( amount <= withdrawableBalance, 'LS1Staking: Withdraw exceeds inactive balance' ); // Decrease the staker's current and next inactive balance. Reverts if balance is insufficient. _decreaseCurrentAndNextInactiveBalance(staker, amount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit Transfer(msg.sender, address(0), amount); emit WithdrewStake(staker, recipient, amount); } // ============ Private Functions ============ function _withdrawDebt( address staker, address recipient, uint256 amount ) private { // Get old amounts and revert if there is not enough to withdraw. uint256 oldDebtBalance = _settleStakerDebtBalance(staker); require( amount <= oldDebtBalance, 'LS1Staking: Withdraw debt exceeds debt owed' ); uint256 oldDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; require( amount <= oldDebtAvailable, 'LS1Staking: Withdraw debt exceeds amount available' ); // Caculate updated amounts and update storage. uint256 newDebtBalance = oldDebtBalance.sub(amount); uint256 newDebtAvailable = oldDebtAvailable.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = newDebtAvailable; // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit WithdrewDebt(staker, recipient, amount, newDebtBalance); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Rewards } from './LS1Rewards.sol'; /** * @title LS1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Internal functions may revert if epoch zero has not started. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Available for borrowing; earning staking rewards; cannot be withdrawn by staker. * - inactive: Unavailable for borrowing; does not earn rewards; can be withdrawn by the staker. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. Also, inactive user balances make use of the shortfallCounter field as * described below. * * INACTIVE BALANCE ACCOUNTING: * * Inactive funds may be subject to pro-rata socialized losses in the event of a shortfall where * a borrower is late to pay back funds that have been requested for withdrawal. We track losses * via indexes. Each index represents the fraction of inactive funds that were converted into * debt during a given shortfall event. Each staker inactive balance stores a cached shortfall * counter, representing the number of shortfalls that occurred in the past relative to when the * balance was last updated. * * Any losses incurred by an inactive balance translate into an equal credit to that staker's * debt balance. See LS1DebtAccounting for more info about how the index is calculated. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via LS1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards or debt balances. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract LS1StakedBalances is LS1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ uint256 internal constant SHORTFALL_INDEX_BASE = 1e36; // ============ Events ============ event ReceivedDebt( address indexed staker, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get a staker's debt balance, after accounting for unsettled shortfalls. * Note that this does not modify _STAKER_DEBT_BALANCES_, so the debt balance must still be * settled before it can be withdrawn. * * @param staker The staker to get the balance of. * * @return The settled debt balance. */ function getStakerDebtBalance( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (, uint256 newDebtAmount) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return _STAKER_DEBT_BALANCES_[staker].add(newDebtAmount); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleStakerDebtBalance( address staker ) internal returns (uint256) { // Settle the inactive balance to settle any new debt. _settleBalance(staker, false); // Return the settled debt balance. return _STAKER_DEBT_BALANCES_[staker]; } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } function _applyShortfall( uint256 shortfallAmount, uint256 shortfallIndex ) internal { // Decrease the total inactive balance. _decreaseCurrentAndNextBalances(address(0), false, shortfallAmount); _SHORTFALLS_.push(LS1Types.Shortfall({ epoch: getCurrentEpoch().toUint16(), index: shortfallIndex.toUint224() })); } /** * @dev Does the same thing as _settleBalance() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeSettleUserInactiveBalance( address staker, uint256 maxEpoch ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = _failsafeLoadUserInactiveBalanceForUpdate(balancePtr, staker, maxEpoch); _storeBalance(balancePtr, balance); } /** * @dev Sets the user inactive balance to zero. See LS1Failsafe. * * Since the balance will never be settled, the staker loses any debt balance that they would * have otherwise been entitled to from shortfall losses. * * Also note that we don't update the total inactive balance, but this is fine. */ function _failsafeDeleteUserInactiveBalance( address staker ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = LS1Types.StoredBalance({ currentEpoch: 0, currentEpochBalance: 0, nextEpochBalance: 0, shortfallCounter: 0 }); _storeBalance(balancePtr, balance); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (LS1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function modifies state, and so the balance MUST be stored afterwards. * - For active balances: if a rollover occurs, rewards are settled to the epoch boundary. * - For inactive user balances: if a shortfall occurs, the user's debt balance is increased. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (LS1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( LS1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Total inactive balance. if (maybeStaker == address(0)) { return _loadTotalInactiveBalance(balancePtr); } // User inactive balance. (LS1Types.StoredBalance memory balance, uint256 newStakerDebt) = _loadUserInactiveBalance(balancePtr); if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[maybeStaker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[maybeStaker] = newDebtBalance; emit ReceivedDebt(maybeStaker, newStakerDebt, newDebtBalance); } return balance; } function _loadActiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns ( LS1Types.StoredBalance memory, uint256, uint256, bool ) { LS1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadTotalInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } function _loadUserInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory, uint256) { LS1Types.StoredBalance memory balance = balancePtr; uint256 currentEpoch = getCurrentEpoch(); // If there is no non-zero balance, sync the epoch number and shortfall counter and exit. // Note: Next inactive balance is always >= current, so we only need to check next. if (balance.nextEpochBalance == 0) { balance.currentEpoch = currentEpoch.toUint16(); balance.shortfallCounter = _SHORTFALLS_.length.toUint16(); return (balance, 0); } // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } return (balance, newStakerDebt); } function _applyShortfallsToBalance( LS1Types.StoredBalance memory balance ) private view returns (LS1Types.StoredBalance memory, uint256) { // Get the cached and global shortfall counters. uint256 shortfallCounter = uint256(balance.shortfallCounter); uint256 globalShortfallCounter = _SHORTFALLS_.length; // If the counters are in sync, then there is nothing to do. if (shortfallCounter == globalShortfallCounter) { return (balance, 0); } // Get the balance params. uint16 cachedEpoch = balance.currentEpoch; uint256 oldCurrentBalance = uint256(balance.currentEpochBalance); // Calculate the new balance after applying shortfalls. // // Note: In theory, this while-loop may render an account's funds inaccessible if there are // too many shortfalls, and too much gas is required to apply them all. This is very unlikely // to occur in practice, but we provide _failsafeLoadUserInactiveBalance() just in case to // ensure recovery is possible. uint256 newCurrentBalance = oldCurrentBalance; while (shortfallCounter < globalShortfallCounter) { LS1Types.Shortfall memory shortfall = _SHORTFALLS_[shortfallCounter]; // Stop applying shortfalls if they are in the future relative to the balance current epoch. if (shortfall.epoch > cachedEpoch) { break; } // Update the current balance to reflect the shortfall. uint256 shortfallIndex = uint256(shortfall.index); newCurrentBalance = newCurrentBalance.mul(shortfallIndex).div(SHORTFALL_INDEX_BASE); // Increment the staker's shortfall counter. shortfallCounter = shortfallCounter.add(1); } // Calculate the loss. // If the loaded balance is stored, this amount must be added to the staker's debt balance. uint256 newStakerDebt = oldCurrentBalance.sub(newCurrentBalance); // Update the balance. balance.currentEpochBalance = newCurrentBalance.toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(newStakerDebt).toUint112(); balance.shortfallCounter = shortfallCounter.toUint16(); return (balance, newStakerDebt); } /** * @dev Store a balance. */ function _storeBalance( LS1Types.StoredBalance storage balancePtr, LS1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; balancePtr.shortfallCounter = balance.shortfallCounter; } /** * @dev Does the same thing as _loadBalanceForUpdate() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeLoadUserInactiveBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address staker, uint256 maxEpoch ) private returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Validate maxEpoch. uint256 currentEpoch = getCurrentEpoch(); uint256 cachedEpoch = uint256(balance.currentEpoch); require( maxEpoch >= cachedEpoch && maxEpoch <= currentEpoch, 'LS1StakedBalances: maxEpoch' ); // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (maxEpoch > cachedEpoch) { balance.currentEpoch = maxEpoch.toUint16(); // Use maxEpoch instead of currentEpoch. balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } // Apply debt if needed. if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[staker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit ReceivedDebt(staker, newStakerDebt, newDebtBalance); } return balance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1EpochSchedule } from './LS1EpochSchedule.sol'; /** * @title LS1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract LS1Rewards is LS1EpochSchedule { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require(distributionEnd >= distributionStart, 'LS1Rewards: Invalid parameters'); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __LS1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Roles } from './LS1Roles.sol'; /** * @title LS1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract LS1EpochSchedule is LS1Roles { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Minimum blackout window. Note: The min epoch length is twice the current blackout window. uint256 private constant MIN_BLACKOUT_WINDOW = 3 days; /// @dev Maximum epoch length. Note: The max blackout window is half the current epoch length. uint256 private constant MAX_EPOCH_LENGTH = 92 days; // Approximately one quarter year. // ============ Events ============ event EpochParametersChanged( LS1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __LS1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'LS1EpochSchedule: Epoch zero must be in future' ); // Don't use _setBlackoutWindow() since the interval is not set yet and validation would fail. _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { _validateParamLengths(interval, _BLACKOUT_WINDOW_); LS1Types.EpochParameters memory epochParameters = LS1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _validateParamLengths(uint256(_EPOCH_PARAMETERS_.interval), blackoutWindow); _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The length of an epoch, in seconds. * @return The start of epoch zero, in seconds. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(block.timestamp >= offset, 'LS1EpochSchedule: Epoch zero has not started'); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } /** * @dev Helper for common validation: verify that the interval and window lengths are valid. */ function _validateParamLengths( uint256 interval, uint256 blackoutWindow ) private pure { require( blackoutWindow.mul(2) <= interval, 'LS1EpochSchedule: Blackout window can be at most half the epoch length' ); require( blackoutWindow >= MIN_BLACKOUT_WINDOW, 'LS1EpochSchedule: Blackout window too large' ); require( interval <= MAX_EPOCH_LENGTH, 'LS1EpochSchedule: Epoch length too small' ); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Roles * @author dYdX * * @dev Defines roles used in the LiquidityStakingV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove users from any of the below roles it manages. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- BORROWER_ADMIN_ROLE * | -> May set borrower allocations and allow/restrict borrowers from borrowing. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * | -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). * | * +-- DEBT_OPERATOR_ROLE * -> May decrease borrow debt and decrease staker debt. */ abstract contract LS1Roles is LS1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant BORROWER_ADMIN_ROLE = keccak256('BORROWER_ADMIN_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); bytes32 public constant DEBT_OPERATOR_ROLE = keccak256('DEBT_OPERATOR_ROLE'); function __LS1Roles_init() internal { // Assign roles to the sender. // // The DEBT_OPERATOR_ROLE, STAKE_OPERATOR_ROLE, and CLAIM_OPERATOR_ROLE roles are not // initially assigned. These can be assigned to other smart contracts to provide additional // functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); _setupRole(BORROWER_ADMIN_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(DEBT_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
Get the borrower allocation for the next epoch. borrower The borrower to get the allocation for. return The borrower's next allocation in hundreds of a percent./
function getAllocationFractionNextEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).nextEpochAllocation); }
5,860,465
/** *Submitted for verification at BscScan.com on 2021-10-30 */ // 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); } // File @openzeppelin/contracts/utils/Address.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol@v4.3.2 pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/Context.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/proxy/utils/Initializable.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File @openzeppelin/contracts/security/ReentrancyGuard.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/ERC20RewardStakingV4.sol pragma solidity ^0.8.4; contract ERC20RewardStakingV4 is ReentrancyGuard, Ownable, Initializable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Rewards to distribute per block. uint256 lastRewardBlock; // Last block number that Rewards distribution occurs. uint256 accRewardTokenPerShare; // Accumulated Rewards per share, times 1e30. See below. } // The stake token IERC20 public STAKE_TOKEN; // The reward token IERC20 public REWARD_TOKEN; // Reward tokens created per block. uint256 public rewardPerBlock; // Keep track of number of tokens staked in case the contract earns reflect fees uint256 public totalStaked = 0; // Keep track of number of reward tokens paid to find remaining reward balance uint256 public totalRewardsPaid = 0; // Keep track of number of reward tokens paid to find remaining reward balance uint256 public totalRewardsAllocated = 0; // Info of each pool. PoolInfo public poolInfo; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 private totalAllocPoint = 0; // The block number when Reward mining starts. uint256 public startBlock; // The block number when mining ends. uint256 public bonusEndBlock; event Deposit(address indexed user, uint256 amount); event DepositRewards(uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event SkimStakeTokenFees(address indexed user, uint256 amount); event LogUpdatePool(uint256 bonusEndBlock, uint256 rewardPerBlock); event EmergencyRewardWithdraw(address indexed user, uint256 amount); event EmergencySweepWithdraw(address indexed user, IERC20 indexed token, uint256 amount); function initialize( IERC20 _stakeToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) external initializer { STAKE_TOKEN = _stakeToken; REWARD_TOKEN = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; // staking pool poolInfo = PoolInfo({ lpToken: _stakeToken, allocPoint: 1000, lastRewardBlock: startBlock, accRewardTokenPerShare: 0 }); totalAllocPoint = 1000; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to - _from; } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock - _from; } } /// @param _bonusEndBlock The block when rewards will end function setBonusEndBlock(uint256 _bonusEndBlock) external onlyOwner { require(_bonusEndBlock > block.number, 'new bonus end block must be greater than current'); bonusEndBlock = _bonusEndBlock; emit LogUpdatePool(bonusEndBlock, rewardPerBlock); } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accRewardTokenPerShare = poolInfo.accRewardTokenPerShare; if (block.number > poolInfo.lastRewardBlock && totalStaked != 0) { uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier * rewardPerBlock * poolInfo.allocPoint / totalAllocPoint; accRewardTokenPerShare = accRewardTokenPerShare + (tokenReward * 1e30 / totalStaked); } return user.amount * accRewardTokenPerShare / 1e30 - user.rewardDebt; } // Update reward variables of the given pool to be up-to-date. function updatePool() public { if (block.number <= poolInfo.lastRewardBlock) { return; } if (totalStaked == 0) { poolInfo.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier * rewardPerBlock * poolInfo.allocPoint / totalAllocPoint; totalRewardsAllocated += tokenReward; poolInfo.accRewardTokenPerShare = poolInfo.accRewardTokenPerShare + (tokenReward * 1e30 / totalStaked); poolInfo.lastRewardBlock = block.number; } /// Deposit staking token into the contract to earn rewards. /// @dev Since this contract needs to be supplied with rewards we are /// sending the balance of the contract if the pending rewards are higher /// @param _amount The amount of staking tokens to deposit function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount * poolInfo.accRewardTokenPerShare / 1e30 - user.rewardDebt; if(pending > 0) { // If rewardBalance is low then revert to avoid losing the user's rewards require(rewardBalance() >= pending, "insufficient reward balance"); safeTransferRewardInternal(address(msg.sender), pending); } } uint256 finalDepositAmount = 0; if (_amount > 0) { uint256 preStakeBalance = STAKE_TOKEN.balanceOf(address(this)); poolInfo.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); finalDepositAmount = STAKE_TOKEN.balanceOf(address(this)) - preStakeBalance; user.amount = user.amount + finalDepositAmount; totalStaked = totalStaked + finalDepositAmount; } user.rewardDebt = user.amount * poolInfo.accRewardTokenPerShare / 1e30; emit Deposit(msg.sender, finalDepositAmount); } /// Withdraw rewards and/or staked tokens. Pass a 0 amount to withdraw only rewards /// @param _amount The amount of staking tokens to withdraw function withdraw(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); uint256 pending = user.amount * poolInfo.accRewardTokenPerShare / 1e30 - user.rewardDebt; if(pending > 0) { // If rewardBalance is low then revert to avoid losing the user's rewards require(rewardBalance() >= pending, "insufficient reward balance"); safeTransferRewardInternal(address(msg.sender), pending); } if(_amount > 0) { user.amount = user.amount - _amount; poolInfo.lpToken.safeTransfer(address(msg.sender), _amount); totalStaked = totalStaked - _amount; } user.rewardDebt = user.amount * poolInfo.accRewardTokenPerShare / 1e30; emit Withdraw(msg.sender, _amount); } /// Obtain the reward balance of this contract /// @return wei balace of conract function rewardBalance() public view returns (uint256) { uint256 balance = REWARD_TOKEN.balanceOf(address(this)); if (STAKE_TOKEN == REWARD_TOKEN) { return balance - totalStaked; } return balance; } /// Get the balance of rewards that have not been harvested /// @return wei balance of rewards left to be paid function getUnharvestedRewards() public view returns (uint256) { return totalRewardsAllocated - totalRewardsPaid; } // Deposit Rewards into contract function depositRewards(uint256 _amount) external { require(_amount > 0, 'Deposit value must be greater than 0.'); REWARD_TOKEN.safeTransferFrom(address(msg.sender), address(this), _amount); emit DepositRewards(_amount); } /// @param _to address to send reward token to /// @param _amount value of reward token to transfer function safeTransferRewardInternal(address _to, uint256 _amount) internal { totalRewardsPaid += _amount; REWARD_TOKEN.safeTransfer(_to, _amount); } /// @dev Obtain the stake balance of this contract function totalStakeTokenBalance() public view returns (uint256) { if (STAKE_TOKEN == REWARD_TOKEN) return totalStaked; return STAKE_TOKEN.balanceOf(address(this)); } /// @dev Obtain the stake token fees (if any) earned by reflect token /// @notice If STAKE_TOKEN == REWARD_TOKEN there are no fees to skim function getStakeTokenFeeBalance() public view returns (uint256) { return totalStakeTokenBalance() - totalStaked; } /* Admin Functions */ /// @param _rewardPerBlock The amount of reward tokens to be given per block function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit LogUpdatePool(bonusEndBlock, rewardPerBlock); } /// @dev Remove excess stake tokens earned by reflect fees function skimStakeTokenFees(address _to) external onlyOwner { uint256 stakeTokenFeeBalance = getStakeTokenFeeBalance(); STAKE_TOKEN.safeTransfer(_to, stakeTokenFeeBalance); emit SkimStakeTokenFees(_to, stakeTokenFeeBalance); } /* Emergency Functions */ // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; poolInfo.lpToken.safeTransfer(address(msg.sender), user.amount); totalStaked = totalStaked - user.amount; user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); } // Withdraw reward. EMERGENCY ONLY. function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { require(_amount <= rewardBalance(), 'not enough rewards'); // Withdraw rewards REWARD_TOKEN.safeTransfer(msg.sender, _amount); emit EmergencyRewardWithdraw(msg.sender, _amount); } /// @notice A public function to sweep accidental ERC20 transfers to this contract. /// Tokens are sent to owner /// @param token The address of the ERC20 token to sweep function sweepToken(IERC20 token) external onlyOwner { require(address(token) != address(STAKE_TOKEN), "can not sweep stake token"); require(address(token) != address(REWARD_TOKEN), "can not sweep reward token"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(msg.sender, balance); emit EmergencySweepWithdraw(msg.sender, token, balance); } }
Obtain the reward balance of this contract return wei balace of conract
function rewardBalance() public view returns (uint256) { uint256 balance = REWARD_TOKEN.balanceOf(address(this)); if (STAKE_TOKEN == REWARD_TOKEN) { return balance - totalStaked; } return balance; }
12,226,843
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title CrowdFunding * @dev create and manage crowdfundings */ contract CrowdFunding { //Project is the struct that we will store the core data for each crowdfunding struct Project { // Title of the crowdfunding string title; // Project identifier address id; // Leader of the crowdfunding campaign address owner; // The amount of wei raised so far uint256 balance; // Amount of founds the project founder wants to collect uint256 ethGoal; // Deadline in seconds (unix timestamp) uint256 deadline; // Bool to show if crowdfunding is sended to the creator bool claimed; } // It is the array of Projects stored in the smart contract // Initially, it was a mapping(address=>Project) but at the end we realised that was easier for us to deal with // an array instead of a mapping that has nested a struct since the logic was pretty more simple regarding // our knowledge with Solidity Project[] projects; // It assigns to each address of project a unique index position of the "projects" array aforedeclared mapping (address => uint256) addressMap; // Ledger with the amount that every user has contributed to a certain project mapping (address => mapping(address => uint256)) donationLedger; // Checks the time of the deadline for the selected project address modifier inTime(bool isInTime, address _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); if(isInTime){ require(block.timestamp <= projects[idx].deadline, "Donations are closed"); }else{ require(block.timestamp > projects[idx].deadline, "Donations are still ongoing"); } _; } // Checks if the sender is the owner of the selected project modifier onlyOwner(bool isOwner, address _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); if(isOwner){ require(msg.sender == projects[idx].owner, "Caller is not the founder"); }else{ require(msg.sender != projects[idx].owner, "Caller is the founder"); } _; } // Checks if the project received as param has achieved the goal initially defined modifier achieved(bool isAchieved, address _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); if(isAchieved){ require(projects[idx].balance >= projects[idx].ethGoal, "Goal is not achieved"); }else{ require(projects[idx].balance < projects[idx].ethGoal, "Goal is achieved"); } _; } // Checks if the balance of the projects has been sent to the creator. modifier fundraised (bool isPaid, address _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); if(isPaid){ require(projects[idx].claimed == true, "Funding is not claimed yet"); }else{ require(projects[idx].claimed == false, "Funding is already claimed"); } _; } //Checks if the amount donated to the project by the user has been claimed modifier claimed (bool isClaimed, address _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); if(isClaimed){ require(donationLedger[msg.sender][_crowdFundingAddress] == 0, "Donation not claimed yet."); }else{ require(donationLedger[msg.sender][_crowdFundingAddress] > 0, "Donation already paid back."); } _; } // ******* PRIVATE FUNCTIONS *********** // Get the index of the project in the "projects" array by an address function getIndexByAddress(address _address) private view returns(uint256){ return addressMap[_address]; } //Get a random address to be the key of a new project function getRandomAddress() private view returns (address) { return address(uint160(uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp))))); } //PUBLIC & EXTERNAL FUNCTIONS // Creates a new project assigning the basic properties to the struct function createProject(string memory _title, uint256 _ethGoal, uint256 _seconds) external { Project storage newProject = projects.push(); address projectId = getRandomAddress(); newProject.id = projectId; newProject.owner = msg.sender; newProject.balance = 0; newProject.title = _title; newProject.ethGoal = _ethGoal * (1 ether); newProject.deadline = block.timestamp + _seconds; newProject.claimed = false; addressMap[projectId]=projects.length -1; } // Makes a donation to the referenced project address transfering the paid amount to the balance of the project // It also stores in the donation ledger the amount donated to such a project // Modifiers: Owner can not donate himself, donation must be before deadline and the crowdfunding can not be achieved yet function makeDonation(IERC20 bfd_token, address _crowdFundingAddress, uint256 _amount) external onlyOwner(false, _crowdFundingAddress) inTime(true, _crowdFundingAddress) achieved(false, _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); require(bfd_token.transferFrom(address(msg.sender),address(this),_amount),"transfer Failed"); projects[idx].balance += _amount; donationLedger[msg.sender][_crowdFundingAddress] += _amount; } // Returns all the projects created in the smart contract function getProjects() external view returns(Project[] memory) { return projects; } // Returns the project by address function getProject(address _address) external view returns(Project memory) { uint256 idx = getIndexByAddress(_address); return projects[idx]; } // Pays to the sender the amount donated to a certain project. To do so, it gets from the donation ledger the amount donated by that user to the selected project id. // Such an amount is removed from the ledger and also from the balance of the project, then is paid back to the sender. // Modifiers: deadline is past, the crowdfunding have not been achieved and finally, the user has not claimed the donation yet function claim(IERC20 bfd_token, address _crowdFundingAddress) external inTime(false, _crowdFundingAddress) achieved(false, _crowdFundingAddress) claimed(false, _crowdFundingAddress) { // Check if the user has already claimed his funds uint256 idx = getIndexByAddress(_crowdFundingAddress); uint256 _amount = donationLedger[msg.sender][_crowdFundingAddress]; projects[idx].balance -= _amount; donationLedger[msg.sender][_crowdFundingAddress] = 0; // Send funds to the donator address bfd_token.transferFrom(address(this),address(msg.sender), _amount); } // Pays the balance of the project to the initiator of the crowfunding. It gets the amount raised and it is paid to the project creator. // The project store that the funding is already paid and the balance now is 0. // Modifiers: Caller has to be the owner,goal has been achieved and the owner has not claimed the funding yet function withdrawFundsByProject(IERC20 bfd_token, address _crowdFundingAddress) public onlyOwner(true, _crowdFundingAddress) achieved(true, _crowdFundingAddress) fundraised(false, _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); uint256 amount = projects[idx].balance; projects[idx].claimed = true; projects[idx].balance = 0; bfd_token.transferFrom(address(this), address(msg.sender), amount); } function getProjectBalance (IERC20 bfd_token, address _crowdFundingAddress) public view returns (uint256){ return bfd_token.balanceOf(_crowdFundingAddress); } function getTotalSupply (IERC20 bfd_token) public view returns (uint256) { return bfd_token.totalSupply(); } }
Pays to the sender the amount donated to a certain project. To do so, it gets from the donation ledger the amount donated by that user to the selected project id. Such an amount is removed from the ledger and also from the balance of the project, then is paid back to the sender. Modifiers: deadline is past, the crowdfunding have not been achieved and finally, the user has not claimed the donation yet Check if the user has already claimed his funds Send funds to the donator address
function claim(IERC20 bfd_token, address _crowdFundingAddress) external inTime(false, _crowdFundingAddress) achieved(false, _crowdFundingAddress) claimed(false, _crowdFundingAddress) { uint256 idx = getIndexByAddress(_crowdFundingAddress); uint256 _amount = donationLedger[msg.sender][_crowdFundingAddress]; projects[idx].balance -= _amount; donationLedger[msg.sender][_crowdFundingAddress] = 0; bfd_token.transferFrom(address(this),address(msg.sender), _amount); }
6,371,065
./partial_match/1/0xf46A6E6A31c41e78d38040cb0442855723554C93/sources/AllocatedCrowdsale.sol
Don't mess the dates
function isSane() public constant returns (bool); function finalizeCrowdsale(); } function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { owner = msg.sender; token = FractionalERC20(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if(multisigWallet == 0) { throw; } if(_start == 0) { throw; } startsAt = _start; if(_end == 0) { throw; } endsAt = _end; if(startsAt >= endsAt) { throw; } }
3,655,926
./partial_match/1/0x629836d92E13A7728DCfb9fBa40B2377e528dfb0/sources/CypherBank.sol
our calculation relies on the token supply, so we need supply. Doh.
function sellPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _devexit = SafeMath.div(SafeMath.mul(_ethereum, 5), 100); uint256 _taxedEthereum1 = SafeMath.sub(_ethereum, _dividends); uint256 _taxedEthereum = SafeMath.sub(_taxedEthereum1, _devexit); return _taxedEthereum; } }
2,894,107
./partial_match/4/0x7f1BabC962221C78b1412Cea08D191A7Ed391Bd3/sources/Lemniscate.sol
Transfer tokens from the caller to a new holder. Remember, there's a 10% fee here as well./ setup make sure we have the requested tokens withdraw all outstanding dividends first liquify 10% of the tokens that are transfered these are dispersed to shareholders burn the fee tokens exchange tokens update dividend trackers disperse dividends among holders fire event ERC20
function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool) { require(_toAddress != address(0)); address _customerAddress = msg.sender; require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if(myDividends(true) > 0) withdraw(); uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToWrappedBTC_(_tokenFee); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_customerAddress] -= (int256) (SafeMath.mul(profitPerShare_, _amountOfTokens)); payoutsTo_[_toAddress] += (int256) (SafeMath.mul(profitPerShare_, _taxedTokens)); profitPerShare_ = SafeMath.add(profitPerShare_, SafeMath.div(SafeMath.mul(_dividends, magnitude), tokenSupply_)); emit Transfer(_customerAddress, _toAddress, _amountOfTokens); return true; } =================================*/
8,503,721
./full_match/5/0x5Fc847Ab7e97787808c772571f496F9F4ac0B346/sources/contracts/Crowdfunding.sol
Setup a new campaign Check if campaign deadline is in the past Fill the new campaign with parameters Increment number of campaigns Return the last added campaign
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image ) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require(campaign.deadline < block.timestamp, "The deadline should be a date in the future!"); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns - 1; }
11,628,687
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2020-03-04 */ pragma solidity 0.6.11; pragma experimental ABIEncoderV2; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Compound"; /// @notice EIP-20 token symbol for this token string public constant symbol = "COMP"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 10000000e18; // 10 million Comp /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups address public owner_address; address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _owner_address, address _timelock_address ) public { name = _name; symbol = _symbol; owner_address = _owner_address; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(owner_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { FRAX = FRAXStablecoin(frax_contract_address); } function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance { FXS_DAO_min = min_FXS; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public owner_address; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner_address || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public { name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); owner_address = _creator_address; _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { fxs_address = _fxs_address; } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setController(address _controller_address) external onlyByOwnerOrGovernance { controller_address = _controller_address; } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../../Math/SafeMath.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private owner_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS == true){ FXS.transfer(msg.sender, FXSAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } /* ========== EVENTS ========== */ } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, 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 { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxPoolInvestorForV2 ====================== // ==================================================================== import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/Variants/Comp.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import "../Frax/Pools/FraxPool.sol"; import "./yearn/IyUSDC_V2_Partial.sol"; import "./aave/IAAVELendingPool_Partial.sol"; import "./aave/IAAVE_aUSDC_Partial.sol"; import "./compound/ICompComptrollerPartial.sol"; import "./compound/IcUSDC_Partial.sol"; // Lower APY: yearn, AAVE, Compound // Higher APY: KeeperDAO, BZX, Harvest contract FraxPoolInvestorForV2 is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXShares private FXS; FRAXStablecoin private FRAX; FraxPool private pool; // Pools and vaults IyUSDC_V2_Partial private yUSDC_V2 = IyUSDC_V2_Partial(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); IAAVELendingPool_Partial private aaveUSDC_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); IAAVE_aUSDC_Partial private aaveUSDC_Token = IAAVE_aUSDC_Partial(0xBcca60bB61934080951369a648Fb03DF4F96263C); IcUSDC_Partial private cUSDC = IcUSDC_Partial(0x39AA39c021dfbaE8faC545936693aC917d5E7563); // Reward Tokens Comp private COMP = Comp(0xc00e94Cb662C3520282E6f5717214004A7f26888); ICompComptrollerPartial private CompController = ICompComptrollerPartial(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public collateral_address; address public pool_address; address public owner_address; address public timelock_address; address public custodian_address; uint256 public immutable missing_decimals; // Max amount of collateral this contract can borrow from the FraxPool uint256 public borrow_cap = uint256(20000e6); // Amount the contract borrowed uint256 public borrowed_balance = 0; uint256 public borrowed_historical = 0; uint256 public paid_back_historical = 0; // Allowed strategies (can eventually be made into an array) bool public allow_yearn = true; bool public allow_aave = true; bool public allow_compound = true; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _owner_address, address _custodian_address, address _timelock_address ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); timelock_address = _timelock_address; owner_address = _owner_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /* ========== VIEWS ========== */ function showAllocations() external returns (uint256[5] memory allocations) { // IMPORTANT // Should ONLY be used externally, because it may fail if any one of the functions below fail // All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC allocations[0] = collateral_token.balanceOf(address(this)); // Unallocated allocations[1] = (yUSDC_V2.balanceOf(address(this))).mul(yUSDC_V2.pricePerShare()).div(1e6); // yearn allocations[2] = aaveUSDC_Token.balanceOf(address(this)); // AAVE allocations[3] = (cUSDC.balanceOf(address(this)).mul(cUSDC.exchangeRateStored()).div(1e18)); // Compound. Note that cUSDC is E8 uint256 sum_tally = 0; for (uint i = 1; i < 5; i++){ if (allocations[i] > 0){ sum_tally = sum_tally.add(allocations[i]); } } allocations[4] = sum_tally; // Total Staked } function showRewards() external returns (uint256[1] memory rewards) { // IMPORTANT // Should ONLY be used externally, because it may fail if COMP.balanceOf() fails rewards[0] = COMP.balanceOf(address(this)); // COMP } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to function function collatDollarBalance() public returns (uint256) { return borrowed_balance; } // This is basically a workaround to transfer USDC from the FraxPool to this investor contract // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract // It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS // The burn can be called separately later on function mintRedeemPart1(uint256 frax_amount) public onlyByOwnerOrGovernance { require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off'); uint256 redemption_fee = pool.redemption_fee(); uint256 col_price_usd = pool.getCollateralPrice(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals); uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6); expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd); require(borrowed_balance.add(expected_collat_amount) <= borrow_cap, "Borrow cap reached"); borrowed_balance = borrowed_balance.add(expected_collat_amount); borrowed_historical = borrowed_historical.add(expected_collat_amount); // Mint the frax FRAX.pool_mint(address(this), frax_amount); // Redeem the frax FRAX.approve(address(pool), frax_amount); pool.redeemFractionalFRAX(frax_amount, 0, 0); } function mintRedeemPart2() public onlyByOwnerOrGovernance { pool.collectRedemption(); } function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance { // Still paying back principal if (amount <= borrowed_balance) { borrowed_balance = borrowed_balance.sub(amount); } // Pure profits else { borrowed_balance = 0; } paid_back_historical = paid_back_historical.add(amount); collateral_token.transfer(address(pool), amount); } function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ========== yearn V2 ========== */ function yDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_yearn, 'yearn strategy is currently off'); collateral_token.approve(address(yUSDC_V2), USDC_amount); yUSDC_V2.deposit(USDC_amount); } function yWithdrawUSDC(uint256 yUSDC_amount) public onlyByOwnerOrGovernance { yUSDC_V2.withdraw(yUSDC_amount); } /* ========== AAVE V2 ========== */ function aaveDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_aave, 'AAVE strategy is currently off'); collateral_token.approve(address(aaveUSDC_Pool), USDC_amount); aaveUSDC_Pool.deposit(collateral_address, USDC_amount, address(this), 0); } function aaveWithdrawUSDC(uint256 aUSDC_amount) public onlyByOwnerOrGovernance { aaveUSDC_Pool.withdraw(collateral_address, aUSDC_amount, address(this)); } /* ========== Compound cUSDC + COMP ========== */ function compoundMint_cUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_compound, 'Compound strategy is currently off'); collateral_token.approve(address(cUSDC), USDC_amount); cUSDC.mint(USDC_amount); } function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnerOrGovernance { // NOTE that cUSDC is E8, NOT E6 cUSDC.redeem(cUSDC_amount); } function compoundCollectCOMP() public onlyByOwnerOrGovernance { CompController.claimComp(address(this)); } /* ========== Custodian ========== */ function withdrawRewards() public onlyCustodian { COMP.transfer(custodian_address, COMP.balanceOf(address(this))); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance { custodian_address = _custodian_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setBorrowCap(uint256 _borrow_cap) external onlyByOwnerOrGovernance { borrow_cap = _borrow_cap; } function setAllowedStrategies(bool _yearn, bool _aave, bool _compound) external onlyByOwnerOrGovernance { allow_yearn = _yearn; allow_aave = _aave; allow_compound = _compound; } function emergencyRecoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0xc6845a5c768bf8d7681249f8927877efda425baf#code // Address [0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVELendingPool_Partial is IERC20 { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0xbCe3076b0d8EB2f640D4089A4929fE8c1a438213#code // Address [0xBcca60bB61934080951369a648Fb03DF4F96263C] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVE_aUSDC_Partial is IERC20 { } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // Original at https://etherscan.io/address/0xbe7616B06f71e363A310Aa8CE8aD99654401ead7#code // Address [0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B] used is a proxy // Some functions were omitted for brevity. See the contract for details interface ICompComptrollerPartial { function claimComp(address holder) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0x39aa39c021dfbae8fac545936693ac917d5e7563#code // Some functions were omitted for brevity. See the contract for details // https://compound.finance/docs/ctokens interface IcUSDC_Partial is IERC20 { function mint(uint mintAmount) external returns (uint); // redeemAmount = # of cUSDC function redeem(uint redeemAmount) external returns (uint); // redeemAmount = # of USDC function redeemUnderlying(uint redeemAmount) external returns (uint); // Multiply this by the E8 balance of cUSDC, then divide the product by E16 function exchangeRateStored() external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../../ERC20/IERC20.sol'; // https://etherscan.io/address/0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9 // Some functions were omitted for brevity. See the contract for details interface IyUSDC_V2_Partial is IERC20 { function balance() external returns (uint); function available() external returns (uint); function earn() external; function deposit(uint _amount) external; function withdraw(uint _shares) external; function pricePerShare() external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle { using FixedPoint for *; address owner_address; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair owner_address = _owner_address; timelock_address = _timelock_address; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); // this matches the CREATE2 in UniswapV2Factory.createPair } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
IMPORTANT Should ONLY be used externally, because it may fail if any one of the functions below fail All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC
function showAllocations() external returns (uint256[5] memory allocations) { uint256 sum_tally = 0; for (uint i = 1; i < 5; i++){ if (allocations[i] > 0){ sum_tally = sum_tally.add(allocations[i]); } } }
9,958,518
./partial_match/1/0x9CCb1Ce08378447263A4FD378BF0f0f35486AAA9/sources/AccessModule.sol
enableWhitelist(); whitelist is disabled by default for testnet, will be enabled by default for mainnet
function isOperationAllowed(Operation operation, address sender) external view returns(bool); } pragma solidity ^0.5.12; function initialize(address _pool) public initializer { Module.initialize(_pool); Pausable.initialize(_msgSender()); WhitelistedRole.initialize(_msgSender()); }
4,044,108
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; pragma abicoder v2; import "./StakingLockable.sol"; /// @author umb.network /// @notice Math is based on synthetix staking contract /// Contract allows to stake and lock tokens. For rUMB tokens only locking option is available. /// When locking user choose period and based on period multiplier is apply to the amount (boost). /// If pool is set for rUMB1->rUMB2, (rUmbPool) then rUMB2 can be locked as well contract StakingLens { struct LockData { uint256 period; uint256 multiplier; } /// @dev returns amount of all staked and locked tokens including bonuses function balanceOf(StakingLockable _pool, address _account) external view returns (uint256) { (uint96 umbBalance, uint96 lockedWithBonus,,,) = _pool.balances(_account); return umbBalance + lockedWithBonus; } function getRewardForDuration(StakingLockable _pool) external view returns (uint256) { (, uint32 rewardsDuration,,) = _pool.timeData(); return _pool.rewardRate() * rewardsDuration; } function rewards(StakingLockable _pool, address _user) external view returns (uint256) { (,,,,uint96 userRewards) = _pool.balances(_user); return userRewards; } /// @notice returns array of max 100 booleans, where index corresponds to lock id. `true` means lock can be withdraw function getVestedLockIds(StakingLockable _pool, address _account, uint256 _offset) external view returns (bool[] memory results) { (,,uint256 nextLockIndex,,) = _pool.balances(_account); uint256 batch = 100; if (nextLockIndex == 0) return results; if (nextLockIndex <= _offset) return results; uint256 end = _offset + batch > nextLockIndex ? nextLockIndex : _offset + batch; results = new bool[](end); for (uint256 i = _offset; i < end; i++) { (,,, uint32 unlockDate,, uint32 withdrawnAt) = _pool.locks(_account, i); results[i] = withdrawnAt == 0 && unlockDate <= block.timestamp; } } /// @notice returns array of max 100 booleans, where index corresponds to lock id. /// `true` means lock was not withdrawn yet function getActiveLockIds(StakingLockable _pool, address _account, uint256 _offset) external view returns (bool[] memory results) { (,,uint256 nextLockIndex,,) = _pool.balances(_account); uint256 batch = 100; if (nextLockIndex == 0) return results; if (nextLockIndex <= _offset) return results; uint256 end = _offset + batch > nextLockIndex ? nextLockIndex : _offset + batch; results = new bool[](end); for (uint256 i = _offset; i < end; i++) { (,,,,, uint32 withdrawnAt) = _pool.locks(_account, i); results[i] = withdrawnAt == 0; } } function getPeriods(StakingLockable _pool, address _token) external view returns (uint256[] memory periods) { return _pool.getPeriods(_token); } function getPeriodsAndMultipliers(StakingLockable _pool, address _token) external view returns (LockData[] memory lockData) { uint256[] memory periods = _pool.getPeriods(_token); uint256 n = periods.length; lockData = new LockData[](n); for (uint256 i; i < n; i++) { lockData[i] = LockData(periods[i], _pool.multipliers(_token, periods[i])); } } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Inheritance import "../interfaces/IStakingRewards.sol"; import "../interfaces/Pausable.sol"; import "../interfaces/IBurnableToken.sol"; import "../interfaces/RewardsDistributionRecipient.sol"; import "../interfaces/OnDemandToken.sol"; import "../interfaces/LockSettings.sol"; import "../interfaces/SwappableTokenV2.sol"; /// @author umb.network /// @notice Math is based on synthetix staking contract /// Contract allows to stake and lock tokens. For rUMB tokens only locking option is available. /// When locking user choose period and based on period multiplier is apply to the amount (boost). /// If pool is set for rUMB1->rUMB2, (rUmbPool) then rUMB2 can be locked as well contract StakingLockable is LockSettings, RewardsDistributionRecipient, ReentrancyGuard, Pausable { struct Times { uint32 periodFinish; uint32 rewardsDuration; uint32 lastUpdateTime; uint96 totalRewardsSupply; } struct Balance { // total supply of UMB = 500_000_000e18, it can be saved using 89bits, so we good with 96 and above // user UMB balance uint96 umbBalance; // amount locked + virtual balance generated using multiplier when locking uint96 lockedWithBonus; uint32 nextLockIndex; uint160 userRewardPerTokenPaid; uint96 rewards; } struct Supply { // staked + raw locked uint128 totalBalance; // virtual balance uint128 totalBonus; } struct Lock { uint8 tokenId; // total supply of UMB can be saved using 89bits, so we good with 96 and above uint120 amount; uint32 lockDate; uint32 unlockDate; uint32 multiplier; uint32 withdrawnAt; } uint8 public constant UMB_ID = 2 ** 0; uint8 public constant RUMB1_ID = 2 ** 1; uint8 public constant RUMB2_ID = 2 ** 2; uint256 public immutable maxEverTotalRewards; address public immutable umb; address public immutable rUmb1; /// @dev this is reward token but we also allow to lock it address public immutable rUmb2; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored; Supply public totalSupply; Times public timeData; /// @dev user => Balance mapping(address => Balance) public balances; /// @dev user => lock ID => Lock mapping(address => mapping(uint256 => Lock)) public locks; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, uint256 bonus); event LockedTokens( address indexed user, address indexed token, uint256 lockId, uint256 amount, uint256 period, uint256 multiplier ); event UnlockedTokens(address indexed user, address indexed token, uint256 lockId, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event FarmingFinished(); event Swap1to2(uint256 swapped); modifier updateReward(address _account) virtual { uint256 newRewardPerTokenStored = rewardPerToken(); rewardPerTokenStored = newRewardPerTokenStored; timeData.lastUpdateTime = uint32(lastTimeRewardApplicable()); if (_account != address(0)) { balances[_account].rewards = uint96(earned(_account)); balances[_account].userRewardPerTokenPaid = uint160(newRewardPerTokenStored); } _; } constructor( address _owner, address _rewardsDistribution, address _umb, address _rUmb1, address _rUmb2 ) Owned(_owner) { require( ( MintableToken(_umb).maxAllowedTotalSupply() + MintableToken(_rUmb1).maxAllowedTotalSupply() + MintableToken(_rUmb2).maxAllowedTotalSupply() ) * MAX_MULTIPLIER / RATE_DECIMALS <= type(uint96).max, "staking overflow" ); require( MintableToken(_rUmb2).maxAllowedTotalSupply() * MAX_MULTIPLIER / RATE_DECIMALS <= type(uint96).max, "rewards overflow" ); require(OnDemandToken(_rUmb2).ON_DEMAND_TOKEN(), "rewardsToken must be OnDemandToken"); umb = _umb; rUmb1 = _rUmb1; rUmb2 = _rUmb2; rewardsDistribution = _rewardsDistribution; timeData.rewardsDuration = 2592000; // 30 days maxEverTotalRewards = MintableToken(_rUmb2).maxAllowedTotalSupply(); } function lockTokens(address _token, uint256 _amount, uint256 _period) external { if (_token == rUmb2 && !SwappableTokenV2(rUmb2).isSwapStarted()) { revert("locking rUMB2 not available yet"); } _lockTokens(msg.sender, _token, _amount, _period); } function unlockTokens(uint256[] calldata _ids) external { _unlockTokensFor(msg.sender, _ids, msg.sender); } function restart(uint256 _rewardsDuration, uint256 _reward) external { setRewardsDuration(_rewardsDuration); notifyRewardAmount(_reward); } // when farming was started with 1y and 12tokens // and we want to finish after 4 months, we need to end up with situation // like we were starting with 4mo and 4 tokens. function finishFarming() external onlyOwner { Times memory t = timeData; require(block.timestamp < t.periodFinish, "can't stop if not started or already finished"); if (totalSupply.totalBalance != 0) { uint32 remaining = uint32(t.periodFinish - block.timestamp); timeData.rewardsDuration = t.rewardsDuration - remaining; } timeData.periodFinish = uint32(block.timestamp); emit FarmingFinished(); } /// @notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. /// In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding. function exit() external { _withdraw(type(uint256).max, msg.sender, msg.sender); _getReward(msg.sender, msg.sender); } /// @notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. /// In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding. function exitAndUnlock(uint256[] calldata _lockIds) external { _withdraw(type(uint256).max, msg.sender, msg.sender); _unlockTokensFor(msg.sender, _lockIds, msg.sender); _getReward(msg.sender, msg.sender); } function stake(uint256 _amount) external { _stake(umb, msg.sender, _amount, 0); } function getReward() external { _getReward(msg.sender, msg.sender); } function swap1to2() public { if (!SwappableTokenV2(rUmb2).isSwapStarted()) return; uint256 myBalance = IERC20(rUmb1).balanceOf(address(this)); if (myBalance == 0) return; IBurnableToken(rUmb1).burn(myBalance); OnDemandToken(rUmb2).mint(address(this), myBalance); emit Swap1to2(myBalance); } /// @dev when notifying about amount, we don't have to mint or send any tokens, reward tokens will be mint on demand /// this method is used to restart staking function notifyRewardAmount( uint256 _reward ) override public onlyRewardsDistribution updateReward(address(0)) { // this method can be executed on its own as well, I'm including here to not need to remember about it swap1to2(); Times memory t = timeData; uint256 newRewardRate; if (block.timestamp >= t.periodFinish) { newRewardRate = _reward / t.rewardsDuration; } else { uint256 remaining = t.periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; newRewardRate = (_reward + leftover) / t.rewardsDuration; } require(newRewardRate != 0, "invalid rewardRate"); rewardRate = newRewardRate; // always increasing by _reward even if notification is in a middle of period // because leftover is included uint256 totalRewardsSupply = timeData.totalRewardsSupply + _reward; require(totalRewardsSupply <= maxEverTotalRewards, "rewards overflow"); timeData.totalRewardsSupply = uint96(totalRewardsSupply); timeData.lastUpdateTime = uint32(block.timestamp); timeData.periodFinish = uint32(block.timestamp + t.rewardsDuration); emit RewardAdded(_reward); } function setRewardsDuration(uint256 _rewardsDuration) public onlyRewardsDistribution { require(_rewardsDuration != 0, "empty _rewardsDuration"); require( block.timestamp > timeData.periodFinish, "Previous period must be complete before changing the duration" ); timeData.rewardsDuration = uint32(_rewardsDuration); emit RewardsDurationUpdated(_rewardsDuration); } /// @notice one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. /// In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding. function withdraw(uint256 _amount) public { _withdraw(_amount, msg.sender, msg.sender); } function lastTimeRewardApplicable() public view returns (uint256) { uint256 periodFinish = timeData.periodFinish; return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view returns (uint256 perToken) { Supply memory s = totalSupply; if (s.totalBalance == 0) { return rewardPerTokenStored; } perToken = rewardPerTokenStored + ( (lastTimeRewardApplicable() - timeData.lastUpdateTime) * rewardRate * 1e18 / (s.totalBalance + s.totalBonus) ); } function earned(address _account) virtual public view returns (uint256) { Balance memory b = balances[_account]; uint256 totalBalance = b.umbBalance + b.lockedWithBonus; return (totalBalance * (rewardPerToken() - b.userRewardPerTokenPaid) / 1e18) + b.rewards; } function calculateBonus(uint256 _amount, uint256 _multiplier) public pure returns (uint256 bonus) { if (_multiplier <= RATE_DECIMALS) return 0; bonus = _amount * _multiplier / RATE_DECIMALS - _amount; } /// @param _token token that we allow to stake, validator check should be do outside /// @param _user token owner /// @param _amount amount /// @param _bonus if bonus is 0, means we are staking, bonus > 0 means this is locking function _stake(address _token, address _user, uint256 _amount, uint256 _bonus) internal nonReentrant notPaused updateReward(_user) { uint256 amountWithBonus = _amount + _bonus; require(timeData.periodFinish > block.timestamp, "Stake period not started yet"); require(amountWithBonus != 0, "Cannot stake 0"); // TODO check if we ever need to separate balance and bonuses totalSupply.totalBalance += uint96(_amount); totalSupply.totalBonus += uint128(_bonus); if (_bonus == 0) { balances[_user].umbBalance += uint96(_amount); } else { balances[_user].lockedWithBonus += uint96(amountWithBonus); } // not using safe transfer, because we working with trusted tokens require(IERC20(_token).transferFrom(_user, address(this), _amount), "token transfer failed"); emit Staked(_user, _amount, _bonus); } function _lockTokens(address _user, address _token, uint256 _amount, uint256 _period) internal notPaused { uint256 multiplier = multipliers[_token][_period]; require(multiplier != 0, "invalid period or not supported token"); uint256 stakeBonus = calculateBonus(_amount, multiplier); _stake(_token, _user, _amount, stakeBonus); _addLock(_user, _token, _amount, _period, multiplier); } function _addLock(address _user, address _token, uint256 _amount, uint256 _period, uint256 _multiplier) internal { uint256 newIndex = balances[_user].nextLockIndex; if (newIndex == type(uint32).max) revert("nextLockIndex overflow"); balances[_user].nextLockIndex = uint32(newIndex + 1); Lock storage lock = locks[_user][newIndex]; lock.amount = uint120(_amount); lock.multiplier = uint32(_multiplier); lock.lockDate = uint32(block.timestamp); lock.unlockDate = uint32(block.timestamp + _period); if (_token == rUmb2) lock.tokenId = RUMB2_ID; else if (_token == rUmb1) lock.tokenId = RUMB1_ID; else lock.tokenId = UMB_ID; emit LockedTokens(_user, _token, newIndex, _amount, _period, _multiplier); } // solhint-disable-next-line code-complexity function _unlockTokensFor(address _user, uint256[] calldata _indexes, address _recipient) internal returns (address token, uint256 totalRawAmount) { uint256 totalBonus; uint256 acceptedTokenId; bool isSwapStarted = SwappableTokenV2(rUmb2).isSwapStarted(); for (uint256 i; i < _indexes.length; i++) { (uint256 amount, uint256 bonus, uint256 tokenId) = _markAsUnlocked(_user, _indexes[i]); if (amount == 0) continue; if (acceptedTokenId == 0) { acceptedTokenId = tokenId; token = _idToToken(tokenId); // if token is already rUmb2 means swap started already if (token == rUmb1 && isSwapStarted) { token = rUmb2; acceptedTokenId = RUMB2_ID; } } else if (acceptedTokenId != tokenId) { if (acceptedTokenId == RUMB2_ID && tokenId == RUMB1_ID) { // this lock is for rUMB1 but swap 1->2 is started so we unlock as rUMB2 } else revert("batch unlock possible only for the same tokens"); } emit UnlockedTokens(_user, token, _indexes[i], amount); totalRawAmount += amount; totalBonus += bonus; } if (totalRawAmount == 0) revert("nothing to unlock"); _withdrawUnlockedTokens(_user, token, _recipient, totalRawAmount, totalBonus); } function _withdrawUnlockedTokens( address _user, address _token, address _recipient, uint256 _totalRawAmount, uint256 _totalBonus ) internal { uint256 amountWithBonus = _totalRawAmount + _totalBonus; balances[_user].lockedWithBonus -= uint96(amountWithBonus); totalSupply.totalBalance -= uint96(_totalRawAmount); totalSupply.totalBonus -= uint128(_totalBonus); // note: there is one case when this transfer can fail: // when swap is started by we did not swap rUmb1 -> rUmb2, // in that case we have to execute `swap1to2` // to save gas I'm not including it here, because it is unlikely case require(IERC20(_token).transfer(_recipient, _totalRawAmount), "withdraw unlocking failed"); } function _markAsUnlocked(address _user, uint256 _index) internal returns (uint256 amount, uint256 bonus, uint256 tokenId) { // TODO will storage save gas? Lock memory lock = locks[_user][_index]; if (lock.withdrawnAt != 0) revert("DepositAlreadyWithdrawn"); if (block.timestamp < lock.unlockDate) revert("DepositLocked"); if (lock.amount == 0) return (0, 0, 0); locks[_user][_index].withdrawnAt = uint32(block.timestamp); return (lock.amount, calculateBonus(lock.amount, lock.multiplier), lock.tokenId); } /// @param _amount tokens to withdraw /// @param _user address /// @param _recipient address, where to send tokens, if we migrating token address can be zero function _withdraw(uint256 _amount, address _user, address _recipient) internal nonReentrant updateReward(_user) { Balance memory balance = balances[_user]; if (_amount == type(uint256).max) _amount = balance.umbBalance; else require(balance.umbBalance >= _amount, "withdraw amount to high"); if (_amount == 0) return; // not using safe math, because there is no way to overflow because of above check totalSupply.totalBalance -= uint120(_amount); balances[_user].umbBalance = uint96(balance.umbBalance - _amount); // not using safe transfer, because we working with trusted tokens require(IERC20(umb).transfer(_recipient, _amount), "token transfer failed"); emit Withdrawn(_user, _amount); } /// @param _user address /// @param _recipient address, where to send reward function _getReward(address _user, address _recipient) internal nonReentrant updateReward(_user) returns (uint256 reward) { reward = balances[_user].rewards; if (reward != 0) { balances[_user].rewards = 0; OnDemandToken(address(rUmb2)).mint(_recipient, reward); emit RewardPaid(_user, reward); } } function _idToToken(uint256 _tokenId) internal view returns (address token) { if (_tokenId == RUMB2_ID) token = rUmb2; else if (_tokenId == RUMB1_ID) token = rUmb1; else if (_tokenId == UMB_ID) token = umb; else return address(0); } } // 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 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.7.5; interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; abstract contract Pausable is Owned { bool public paused; event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), "Owner must be set"); // Paused will be false } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface IBurnableToken { function burn(uint256 _amount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; // https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistributor"); _; } function notifyRewardAmount(uint256 reward) virtual external; function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./MintableToken.sol"; abstract contract OnDemandToken is MintableToken { bool constant public ON_DEMAND_TOKEN = true; mapping (address => bool) public minters; event SetupMinter(address minter, bool active); modifier onlyOwnerOrMinter() { address msgSender = _msgSender(); require(owner() == msgSender || minters[msgSender], "access denied"); _; } function setupMinter(address _minter, bool _active) external onlyOwner() { minters[_minter] = _active; emit SetupMinter(_minter, _active); } function setupMinters(address[] calldata _minters, bool[] calldata _actives) external onlyOwner() { for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = _actives[i]; emit SetupMinter(_minters[i], _actives[i]); } } function mint(address _holder, uint256 _amount) external virtual override onlyOwnerOrMinter() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract LockSettings is Ownable { /// @dev decimals for: baseRate, APY, multipliers /// eg for baseRate: 1e6 is 1%, 50e6 is 50% /// eg for multipliers: 1e6 is 1.0x, 3210000 is 3.21x uint256 public constant RATE_DECIMALS = 10 ** 6; uint256 public constant MAX_MULTIPLIER = 5 * RATE_DECIMALS; /// @notice token => period => multiplier mapping(address => mapping(uint256 => uint256)) public multipliers; /// @notice token => period => index in periods array mapping(address => mapping(uint256 => uint256)) public periodIndexes; /// @notice token => periods mapping(address => uint256[]) public periods; event TokenSettings(address indexed token, uint256 period, uint256 multiplier); function removePeriods(address _token, uint256[] calldata _periods) external onlyOwner { for (uint256 i; i < _periods.length; i++) { if (_periods[i] == 0) revert("InvalidSettings"); multipliers[_token][_periods[i]] = 0; _removePeriod(_token, _periods[i]); emit TokenSettings(_token, _periods[i], 0); } } // solhint-disable-next-line code-complexity function setLockingTokenSettings(address _token, uint256[] calldata _periods, uint256[] calldata _multipliers) external onlyOwner { if (_periods.length == 0) revert("EmptyPeriods"); if (_periods.length != _multipliers.length) revert("ArraysNotMatch"); for (uint256 i; i < _periods.length; i++) { if (_periods[i] == 0) revert("InvalidSettings"); if (_multipliers[i] < RATE_DECIMALS) revert("multiplier must be >= 1e6"); if (_multipliers[i] > MAX_MULTIPLIER) revert("multiplier overflow"); multipliers[_token][_periods[i]] = _multipliers[i]; emit TokenSettings(_token, _periods[i], _multipliers[i]); if (_multipliers[i] == 0) _removePeriod(_token, _periods[i]); else _addPeriod(_token, _periods[i]); } } function periodsCount(address _token) external view returns (uint256) { return periods[_token].length; } function getPeriods(address _token) external view returns (uint256[] memory) { return periods[_token]; } function _addPeriod(address _token, uint256 _period) internal { uint256 key = periodIndexes[_token][_period]; if (key != 0) return; periods[_token].push(_period); // periodIndexes are starting from 1, not from 0 periodIndexes[_token][_period] = periods[_token].length; } function _removePeriod(address _token, uint256 _period) internal { uint256 key = periodIndexes[_token][_period]; if (key == 0) return; periods[_token][key - 1] = periods[_token][periods[_token].length - 1]; periodIndexes[_token][_period] = 0; periods[_token].pop(); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/Owned.sol"; import "../interfaces/ISwapReceiver.sol"; /// @title Umbrella Rewards contract V2 /// @author umb.network /// @notice This contract serves Swap functionality for rewards tokens /// @dev It allows to swap itself for other token (main UMB token). abstract contract SwappableTokenV2 is Owned, ERC20 { struct SwapData { // number of tokens swapped so far (no decimals) uint32 swappedSoFar; // used limit since last swap (no decimals) uint32 usedLimit; // daily cup (no decimals) uint32 dailyCup; uint32 dailyCupTimestamp; uint32 swapEnabledAt; } uint256 public constant ONE = 1e18; uint256 public immutable swapStartsOn; ISwapReceiver public immutable umb; SwapData public swapData; event LogStartEarlySwapNow(uint time); event LogSwap(address indexed swappedTo, uint amount); event LogDailyCup(uint newCup); constructor(address _umb, uint32 _swapStartsOn, uint32 _dailyCup) { require(_dailyCup != 0, "invalid dailyCup"); require(_swapStartsOn > block.timestamp, "invalid swapStartsOn"); require(ERC20(_umb).decimals() == 18, "invalid UMB token"); swapStartsOn = _swapStartsOn; umb = ISwapReceiver(_umb); swapData.dailyCup = _dailyCup; } function swapForUMB() external { SwapData memory data = swapData; (uint256 limit, bool fullLimit) = _currentLimit(data); require(limit != 0, "swapping period not started OR limit"); uint256 amountToSwap = balanceOf(msg.sender); require(amountToSwap != 0, "you dont have tokens to swap"); uint32 amountWoDecimals = uint32(amountToSwap / ONE); require(amountWoDecimals <= limit, "daily CUP limit"); swapData.usedLimit = uint32(fullLimit ? amountWoDecimals : data.usedLimit + amountWoDecimals); swapData.swappedSoFar += amountWoDecimals; if (fullLimit) swapData.dailyCupTimestamp = uint32(block.timestamp); _burn(msg.sender, amountToSwap); umb.swapMint(msg.sender, amountToSwap); emit LogSwap(msg.sender, amountToSwap); } function startEarlySwap() external onlyOwner { require(block.timestamp < swapStartsOn, "swap is already allowed"); require(swapData.swapEnabledAt == 0, "swap was already enabled"); swapData.swapEnabledAt = uint32(block.timestamp); emit LogStartEarlySwapNow(block.timestamp); } /// @param _cup daily cup limit (no decimals), eg. if cup=5 means it is 5 * 10^18 tokens function setDailyCup(uint32 _cup) external onlyOwner { swapData.dailyCup = _cup; emit LogDailyCup(_cup); } function isSwapStarted() external view returns (bool) { // will it save gas if I do 2x if?? return block.timestamp >= swapStartsOn || swapData.swapEnabledAt != 0; } function canSwapTokens(address _address) external view returns (bool) { uint256 balance = balanceOf(_address); if (balance == 0) return false; (uint256 limit,) = _currentLimit(swapData); return balance / ONE <= limit; } function currentLimit() external view returns (uint256 limit) { (limit,) = _currentLimit(swapData); limit *= ONE; } function _currentLimit(SwapData memory data) internal view returns (uint256 limit, bool fullLimit) { if (block.timestamp < swapStartsOn && data.swapEnabledAt == 0) return (0, false); fullLimit = block.timestamp - data.dailyCupTimestamp >= 24 hours; limit = fullLimit ? data.dailyCup : data.dailyCup - data.usedLimit; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract Owned is Ownable { constructor(address _owner) { transferOwnership(_owner); } } // 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: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/Owned.sol"; import "../interfaces/IBurnableToken.sol"; /// @author umb.network abstract contract MintableToken is Owned, ERC20, IBurnableToken { uint256 public immutable maxAllowedTotalSupply; uint256 public everMinted; modifier assertMaxSupply(uint256 _amountToMint) { _assertMaxSupply(_amountToMint); _; } // ========== CONSTRUCTOR ========== // constructor (uint256 _maxAllowedTotalSupply) { require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty"); maxAllowedTotalSupply = _maxAllowedTotalSupply; } // ========== MUTATIVE FUNCTIONS ========== // function burn(uint256 _amount) override external { _burn(msg.sender, _amount); } // ========== RESTRICTED FUNCTIONS ========== // function mint(address _holder, uint256 _amount) virtual external onlyOwner() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } function _assertMaxSupply(uint256 _amountToMint) internal { uint256 everMintedTotal = everMinted + _amountToMint; everMinted = everMintedTotal; require(everMintedTotal <= maxAllowedTotalSupply, "total supply limit exceeded"); } } // 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: 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.7.5; interface ISwapReceiver { function swapMint(address _holder, uint256 _amount) external; }
one of the reasons this method can throw is, when we swap for UMB and somebody stake rUMB1 after that. In that case execution of `swapForUMB()` is required (anyone can execute this method) before proceeding.
function exitAndUnlock(uint256[] calldata _lockIds) external { _withdraw(type(uint256).max, msg.sender, msg.sender); _unlockTokensFor(msg.sender, _lockIds, msg.sender); _getReward(msg.sender, msg.sender); }
14,641,452
./full_match/137/0x80ec9bCbD13C4839F63f67305042b196E29EA154/sources/contracts/ERC721Tradable.sol
Mints a token for msg.sender with a tokenURI. return bool/
function claim() internal returns (bool) { uint256 newTokenId = _getNextTokenId(); _mint(msg.sender, newTokenId); _incrementTokenId(); return true; }
4,782,078
pragma solidity >=0.4.22 <0.9.0; //pragma solidity >=0.5.0; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/Doobem.sol"; contract TestDoobem { // The address of the Doobem contract to be tested Doobem doobem = Doobem(DeployedAddresses.Doobem()); // The id of the Job that will be used for testing uint expectedJobId = 8; // The expected Volunteer of Job is this contract address expectedVolunteers = address(this); } // Testing the choose() function function testUserCanChoosejobId() public { uint returnedJobId = Doobem.Volunteer(expectedjobId); Assert.equal(returnedId, expectedjobId,"Choose of the expected job should match what is returned."); } // Testing retrieval of a single job´s owner function testGetVolunteersAddressByJobId() public { address volunteers = doobem.volunteers(expectedjobId); Assert.equal(volunteers, expectedVolunteers, "Owner of the expected job should be this contract"); } // Testing retrieval of all Volunteers function testGetVolunteersAddressByJobId() public { // Store volunteers in memory rather than contract's storage address[8] memory volunteers = doobem.getVolunteers(); Assert.equal(volunteers[expectedJobId], expectedVolunteers, "Volunteer of the expected Job should be this contract"); }
Testing the choose() function
function testUserCanChoosejobId() public { uint returnedJobId = Doobem.Volunteer(expectedjobId); Assert.equal(returnedId, expectedjobId,"Choose of the expected job should match what is returned."); }
2,558,501
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol"; import "multi-token-standard/contracts/interfaces/IERC1155.sol"; import "openzeppelin-solidity/contracts/token/ERC1155/ERC1155Holder.sol"; import "openzeppelin-solidity/contracts/access/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; interface Geyser{ function totalStakedFor(address addr) external view returns(uint256); } /** * @title Stater Lending Contract * @notice Contract that allows users to leverage their NFT assets * @author Stater */ contract LendingData is ERC721Holder, ERC1155Holder, Ownable { // @notice OpenZeppelin's SafeMath library using SafeMath for uint256; enum TimeScale{ MINUTES, HOURS, DAYS, WEEKS } // The address of the Stater NFT collection address public nftAddress; //0xcb13DC836C2331C669413352b836F1dA728ce21c // The address of the Stater Geyser Contract address[] public geyserAddressArray; //[0xf1007ACC8F0229fCcFA566522FC83172602ab7e3] // The address of the Stater Promissory Note Contract address public promissoryNoteContractAddress; uint256[] public staterNftTokenIdArray; //[0, 1] // 50=50% uint32 public discountNft = 50; // 50=50% uint32 public discountGeyser = 50; // 100 = 1% uint32 public lenderFee = 100; // Incremental value used for loan ids uint256 public loanID; // Loan to value(ltv). 600=60% uint256 public ltv = 600; uint256 public installmentFrequency = 1; TimeScale public installmentTimeScale = TimeScale.WEEKS; // 20 =20% uint256 public interestRate = 20; // 40=40% out of intersetRate uint256 public interestRateToStater = 40; event NewLoan(uint256 indexed loanId, address indexed owner, uint256 creationDate, address indexed currency, Status status, string creationId); event LoanApproved(uint256 indexed loanId, address indexed lender, uint256 approvalDate, uint256 loanPaymentEnd, Status status); event LoanCancelled(uint256 indexed loanId, uint256 cancellationDate, Status status); event ItemsWithdrawn(uint256 indexed loanId, address indexed requester, Status status); event LoanPayment(uint256 indexed loanId, uint256 paymentDate, uint256 installmentAmount, uint256 amountPaidAsInstallmentToLender, uint256 interestPerInstallement, uint256 interestToStaterPerInstallement, Status status); enum Status{ UNINITIALIZED, // will be removed in the future -- not used LISTED, // after the loan have been created --> the next status will be APPROVED APPROVED, // in this status the loan has a lender -- will be set after approveLoan() DEFAULTED, // will be removed in the future -- not used LIQUIDATED, // the loan will have this status after all installments have been paid CANCELLED, // only if loan is LISTED WITHDRAWN // the final status, the collateral returned to the borrower or to the lender } enum TokenType{ ERC721, ERC1155 } struct Loan { address[] nftAddressArray; // the adderess of the ERC721 address payable borrower; // the address who receives the loan address payable lender; // the address who gives/offers the loan to the borrower address currency; // the token that the borrower lends, address(0) for ETH Status status; // the loan status uint256[] nftTokenIdArray; // the unique identifier of the NFT token that the borrower uses as collateral uint256 loanAmount; // the amount, denominated in tokens (see next struct entry), the borrower lends uint256 assetsValue; // important for determintng LTV which has to be under 50-60% uint256 loanStart; // the point when the loan is approved uint256 loanEnd; // the point when the loan is approved to the point when it must be paid back to the lender uint256 nrOfInstallments; // the number of installments that the borrower must pay. uint256 installmentAmount; // amount expected for each installment uint256 amountDue; // loanAmount + interest that needs to be paid back by borrower uint256 paidAmount; // the amount that has been paid back to the lender to date uint256 defaultingLimit; // the number of installments allowed to be missed without getting defaulted uint256 nrOfPayments; // the number of installments paid TokenType[] nftTokenTypeArray; // the token types : ERC721 , ERC1155 , ... } // @notice Mapping for all the loans mapping(uint256 => Loan) public loans; // @notice Mapping for all the loans that are approved by the owner in order to be used in the promissory note mapping(uint256 => address) public promissoryPermissions; /** * @notice Construct a new lending contract * @param _nftAddress The address of the Stater nft collection * @param _promissoryNoteContractAddress The address of the Stater Promissory Note contract * @param _geyserAddressArray The address of the Stater geyser contract * @param _staterNftTokenIdArray Array of the stater nft token IDs */ constructor(address _nftAddress, address _promissoryNoteContractAddress, address[] memory _geyserAddressArray, uint256[] memory _staterNftTokenIdArray) { nftAddress = _nftAddress; geyserAddressArray = _geyserAddressArray; staterNftTokenIdArray = _staterNftTokenIdArray; promissoryNoteContractAddress = _promissoryNoteContractAddress; } // Borrower creates a loan /** * @notice The borrower creates the loan using the NFT as collateral * @param loanAmount The amount of the loan * @param nrOfInstallments Loan's number of installments * @param currency ETH or custom ERC20 * @param assetsValue The value of the assets * @param nftAddressArray Array of nft addresses in the loan bundle. * @param nftTokenIdArray Array of nft token IDs in the loan bundle. * @param creationId ID used to identify loan creation event in the stater database. * @param nftTokenTypeArray The token types : ERC721 , ERC115 */ function createLoan( uint256 loanAmount, uint256 nrOfInstallments, address currency, uint256 assetsValue, address[] calldata nftAddressArray, uint256[] calldata nftTokenIdArray, string calldata creationId, TokenType[] memory nftTokenTypeArray ) external { require(nrOfInstallments > 0, "Loan must have at least 1 installment"); require(loanAmount > 0, "Loan amount must be higher than 0"); require(nftAddressArray.length > 0, "Loan must have atleast 1 NFT"); require(nftAddressArray.length == nftTokenIdArray.length && nftTokenIdArray.length == nftTokenTypeArray.length, "NFT provided informations are missing or incomplete"); // Compute loan to value ratio for current loan application require(_percent(loanAmount, assetsValue) <= ltv, "LTV exceeds maximum limit allowed"); // Computing the defaulting limit if ( nrOfInstallments <= 3 ) loans[loanID].defaultingLimit = 1; else if ( nrOfInstallments <= 5 ) loans[loanID].defaultingLimit = 2; else if ( nrOfInstallments >= 6 ) loans[loanID].defaultingLimit = 3; // Set loan fields loans[loanID].nftTokenIdArray = nftTokenIdArray; loans[loanID].loanAmount = loanAmount; loans[loanID].assetsValue = assetsValue; loans[loanID].amountDue = loanAmount.mul(interestRate.add(100)).div(100); // interest rate >> 20% loans[loanID].nrOfInstallments = nrOfInstallments; loans[loanID].installmentAmount = loans[loanID].amountDue.mod(nrOfInstallments) > 0 ? loans[loanID].amountDue.div(nrOfInstallments).add(1) : loans[loanID].amountDue.div(nrOfInstallments); loans[loanID].status = Status.LISTED; loans[loanID].nftAddressArray = nftAddressArray; loans[loanID].borrower = msg.sender; loans[loanID].currency = currency; loans[loanID].nftTokenTypeArray = nftTokenTypeArray; // Transfer the items from lender to stater contract _transferItems( msg.sender, address(this), nftAddressArray, nftTokenIdArray, nftTokenTypeArray ); // Fire event emit NewLoan(loanID, msg.sender, block.timestamp, currency, Status.LISTED, creationId); ++loanID; } /** * @notice The lender will approve the loan * @param loanId The id of the loan */ function approveLoan(uint256 loanId) external payable { require(loans[loanId].lender == address(0), "Someone else payed for this loan before you"); require(loans[loanId].paidAmount == 0, "This loan is currently not ready for lenders"); require(loans[loanId].status == Status.LISTED, "This loan is not currently ready for lenders, check later"); uint256 discount = calculateDiscount(msg.sender); // We check if currency is ETH if ( loans[loanId].currency == address(0) ) require(msg.value >= loans[loanId].loanAmount.add(loans[loanId].loanAmount.div(lenderFee).div(discount)),"Not enough currency"); // Borrower assigned , status is 1 , first installment ( payment ) completed loans[loanId].lender = msg.sender; loans[loanId].loanEnd = block.timestamp.add(loans[loanId].nrOfInstallments.mul(generateInstallmentFrequency())); loans[loanId].status = Status.APPROVED; loans[loanId].loanStart = block.timestamp; // We send the tokens here _transferTokens(msg.sender,loans[loanId].borrower,loans[loanId].currency,loans[loanId].loanAmount,loans[loanId].loanAmount.div(lenderFee).div(discount)); emit LoanApproved( loanId, msg.sender, block.timestamp, loans[loanId].loanEnd, Status.APPROVED ); } // Borrower cancels a loan function cancelLoan(uint256 loanId) external { require(loans[loanId].lender == address(0), "The loan has a lender , it cannot be cancelled"); require(loans[loanId].borrower == msg.sender, "You're not the borrower of this loan"); require(loans[loanId].status != Status.CANCELLED, "This loan is already cancelled"); require(loans[loanId].status == Status.LISTED, "This loan is no longer cancellable"); // We set its validity date as block.timestamp loans[loanId].loanEnd = block.timestamp; loans[loanId].status = Status.CANCELLED; // We send the items back to him _transferItems( address(this), loans[loanId].borrower, loans[loanId].nftAddressArray, loans[loanId].nftTokenIdArray, loans[loanId].nftTokenTypeArray ); emit LoanCancelled( loanId, block.timestamp, Status.CANCELLED ); } /** * @notice Borrower pays installments for the loan * @param loanId The id of the loan */ function payLoan(uint256 loanId) external payable { require(loans[loanId].borrower == msg.sender, "You're not the borrower of this loan"); require(loans[loanId].status == Status.APPROVED, "This loan is no longer in the approval phase, check its status"); require(loans[loanId].loanEnd >= block.timestamp, "Loan validity expired"); require((msg.value > 0 && loans[loanId].currency == address(0) ) || ( loans[loanId].currency != address(0) && msg.value == 0), "Insert the correct tokens"); uint256 paidByBorrower = msg.value > 0 ? msg.value : loans[loanId].installmentAmount; uint256 amountPaidAsInstallmentToLender = paidByBorrower; // >> amount of installment that goes to lender uint256 interestPerInstallement = paidByBorrower.mul(interestRate).div(100); // entire interest for installment uint256 discount = calculateDiscount(msg.sender); uint256 interestToStaterPerInstallement = interestPerInstallement.mul(interestRateToStater).div(100); if ( discount != 1 ){ if ( loans[loanId].currency == address(0) ){ require(msg.sender.send(interestToStaterPerInstallement.div(discount)), "Discount returnation failed"); amountPaidAsInstallmentToLender = amountPaidAsInstallmentToLender.sub(interestToStaterPerInstallement.div(discount)); } interestToStaterPerInstallement = interestToStaterPerInstallement.sub(interestToStaterPerInstallement.div(discount)); } amountPaidAsInstallmentToLender = amountPaidAsInstallmentToLender.sub(interestToStaterPerInstallement); loans[loanId].paidAmount = loans[loanId].paidAmount.add(paidByBorrower); loans[loanId].nrOfPayments = loans[loanId].nrOfPayments.add(paidByBorrower.div(loans[loanId].installmentAmount)); if (loans[loanId].paidAmount >= loans[loanId].amountDue) loans[loanId].status = Status.LIQUIDATED; // We transfer the tokens to borrower here _transferTokens(msg.sender,loans[loanId].lender,loans[loanId].currency,amountPaidAsInstallmentToLender,interestToStaterPerInstallement); emit LoanPayment( loanId, block.timestamp, msg.value, amountPaidAsInstallmentToLender, interestPerInstallement, interestToStaterPerInstallement, loans[loanId].status ); } /** * @notice Borrwoer can withdraw loan items if loan is LIQUIDATED * @notice Lender can withdraw loan items if loan is DEFAULTED * @param loanId The id of the loan */ function terminateLoan(uint256 loanId) external { require(msg.sender == loans[loanId].borrower || msg.sender == loans[loanId].lender, "You can't access this loan"); require((block.timestamp >= loans[loanId].loanEnd || loans[loanId].paidAmount >= loans[loanId].amountDue) || lackOfPayment(loanId), "Not possible to finish this loan yet"); require(loans[loanId].status == Status.LIQUIDATED || loans[loanId].status == Status.APPROVED, "Incorrect state of loan"); require(loans[loanId].status != Status.WITHDRAWN, "Loan NFTs already withdrawn"); if ( lackOfPayment(loanId) ) { loans[loanId].status = Status.WITHDRAWN; loans[loanId].loanEnd = block.timestamp; // We send the items back to lender _transferItems( address(this), loans[loanId].lender, loans[loanId].nftAddressArray, loans[loanId].nftTokenIdArray, loans[loanId].nftTokenTypeArray ); } else { if ( block.timestamp >= loans[loanId].loanEnd && loans[loanId].paidAmount < loans[loanId].amountDue ) { loans[loanId].status = Status.WITHDRAWN; // We send the items back to lender _transferItems( address(this), loans[loanId].lender, loans[loanId].nftAddressArray, loans[loanId].nftTokenIdArray, loans[loanId].nftTokenTypeArray ); } else if ( loans[loanId].paidAmount >= loans[loanId].amountDue ){ loans[loanId].status = Status.WITHDRAWN; // We send the items back to borrower _transferItems( address(this), loans[loanId].borrower, loans[loanId].nftAddressArray, loans[loanId].nftTokenIdArray, loans[loanId].nftTokenTypeArray ); } } emit ItemsWithdrawn( loanId, msg.sender, loans[loanId].status ); } /** * @notice Used by the Promissory Note contract to change the ownership of the loan when the Promissory Note NFT is sold * @param loanIds The ids of the loans that will be transferred to the new owner * @param newOwner The address of the new owner */ function promissoryExchange(uint256[] calldata loanIds, address payable newOwner) external { require(msg.sender == promissoryNoteContractAddress, "You're not whitelisted to access this method"); for (uint256 i = 0; i < loanIds.length; ++i) { require(loans[loanIds[i]].lender != address(0), "One of the loans is not approved yet"); require(promissoryPermissions[loanIds[i]] == msg.sender, "You're not allowed to perform this operation on loan"); loans[loanIds[i]].lender = newOwner; } } /** * @notice Used by the Promissory Note contract to approve a list of loans to be used as a Promissory Note NFT * @param loanIds The ids of the loans that will be approved */ function setPromissoryPermissions(uint256[] calldata loanIds) external { for (uint256 i = 0; i < loanIds.length; ++i) { require(loans[loanIds[i]].lender == msg.sender, "You're not the lender of this loan"); promissoryPermissions[loanIds[i]] = promissoryNoteContractAddress; } } /** * @notice Liquidity mining participants or Stater NFT holders will be able to get some discount * @param requester The address of the requester */ function calculateDiscount(address requester) public view returns(uint256){ for (uint i = 0; i < staterNftTokenIdArray.length; ++i) if ( IERC1155(nftAddress).balanceOf(requester,staterNftTokenIdArray[i]) > 0 ) return uint256(100).div(discountNft); for (uint256 i = 0; i < geyserAddressArray.length; ++i) if ( Geyser(geyserAddressArray[i]).totalStakedFor(requester) > 0 ) return uint256(100).div(discountGeyser); return 1; } /** * @notice This function returns total price (+ fees) * @param loanId The id of the loan */ function getLoanApprovalCost(uint256 loanId) external view returns(uint256) { return loans[loanId].loanAmount.add(loans[loanId].loanAmount.div(lenderFee).div(calculateDiscount(msg.sender))); } /** * @notice * @param loanId The id of the loan */ function getLoanRemainToPay(uint256 loanId) external view returns(uint256) { return loans[loanId].amountDue.sub(loans[loanId].paidAmount); } /** * @notice * @param loanId The id of the loan * @param nrOfInstallments The id of the loan */ function getLoanInstallmentCost( uint256 loanId, uint256 nrOfInstallments ) external view returns( uint256 overallInstallmentAmount, uint256 interestPerInstallement, uint256 interestDiscounted, uint256 interestToStaterPerInstallement, uint256 amountPaidAsInstallmentToLender ) { require(nrOfInstallments <= loans[loanId].nrOfInstallments, "Number of installments too high"); uint256 discount = calculateDiscount(msg.sender); interestDiscounted = 0; overallInstallmentAmount = uint256(loans[loanId].installmentAmount.mul(nrOfInstallments)); interestPerInstallement = uint256(overallInstallmentAmount.mul(interestRate).div(100).div(loans[loanId].nrOfInstallments)); interestDiscounted = interestPerInstallement.mul(interestRateToStater).div(100).div(discount); // amount of interest saved per installment interestToStaterPerInstallement = interestPerInstallement.mul(interestRateToStater).div(100).sub(interestDiscounted); amountPaidAsInstallmentToLender = interestPerInstallement.mul(uint256(100).sub(interestRateToStater)).div(100); } /** * @notice This function checks for unpaid installments * @param loanId The id of the loan */ function lackOfPayment(uint256 loanId) public view returns(bool) { return loans[loanId].status == Status.APPROVED && loans[loanId].loanStart.add(loans[loanId].nrOfPayments.mul(generateInstallmentFrequency())) <= block.timestamp.sub(loans[loanId].defaultingLimit.mul(generateInstallmentFrequency())); } function generateInstallmentFrequency() public view returns(uint256){ if (installmentTimeScale == TimeScale.MINUTES) { return 1 minutes; } else if (installmentTimeScale == TimeScale.HOURS) { return 1 hours; } else if (installmentTimeScale == TimeScale.DAYS) { return 1 days; } return 1 weeks; } /** * @notice Setter function for the discounts * @param _discountNft Discount value for the Stater NFT holders * @param _discountGeyser Discount value for the Stater liquidity mining participants * @param _geyserAddressArray List of the Stater Geyser contracts * @param _staterNftTokenIdArray Array of stater nft token IDs. * @param _nftAddress List of the Stater NFT collections */ function setDiscounts(uint32 _discountNft, uint32 _discountGeyser, address[] calldata _geyserAddressArray, uint256[] calldata _staterNftTokenIdArray, address _nftAddress) external onlyOwner { discountNft = _discountNft; discountGeyser = _discountGeyser; geyserAddressArray = _geyserAddressArray; staterNftTokenIdArray = _staterNftTokenIdArray; nftAddress = _nftAddress; } /** * @notice Setter function * @param _promissoryNoteContractAddress The address of the Stater promissory Note contract * @param _ltv Value of Loan to value * @param _installmentFrequency Value of installment frequency * @param _installmentTimeScale The timescale of all loans. * @param _interestRate Value of interest rate * @param _interestRateToStater Value of interest rate to stater * @param _lenderFee Value of the lender fee */ function setGlobalVariables(address _promissoryNoteContractAddress, uint256 _ltv, uint256 _installmentFrequency, TimeScale _installmentTimeScale, uint256 _interestRate, uint256 _interestRateToStater, uint32 _lenderFee) external onlyOwner { ltv = _ltv; installmentFrequency = _installmentFrequency; installmentTimeScale = _installmentTimeScale; interestRate = _interestRate; interestRateToStater = _interestRateToStater; lenderFee = _lenderFee; promissoryNoteContractAddress = _promissoryNoteContractAddress; } /** * @notice Adds a new geyser address to the list * @param geyserAddress The new geyser address */ function addGeyserAddress(address geyserAddress) external onlyOwner { geyserAddressArray.push(geyserAddress); } /** * @notice Adds a new nft to the list * @param nftId The id of the new nft */ function addNftTokenId(uint256 nftId) external onlyOwner { staterNftTokenIdArray.push(nftId); } /** * @notice Calculates loan to value ration * @param numerator Numerator. * @param denominator Denominator. */ function _percent(uint256 numerator, uint256 denominator) internal pure returns(uint256) { return numerator.mul(10000).div(denominator).add(5).div(10); } /** * @notice Transfer items fron an account to another * @param from From account address. * @param to To account address. * @param nftAddressArray Array of addresses of the nfts to be transfered. * @param nftTokenIdArray Array of token IDs of the nfts to be transfered. * @param nftTokenTypeArray Array of token type of the nfts to be transfered. */ function _transferItems( address from, address to, address[] memory nftAddressArray, uint256[] memory nftTokenIdArray, TokenType[] memory nftTokenTypeArray ) internal { uint256 length = nftAddressArray.length; require(length == nftTokenIdArray.length && nftTokenTypeArray.length == length, "Token infos provided are invalid"); for(uint256 i = 0; i < length; ++i) if ( nftTokenTypeArray[i] == TokenType.ERC721 ) IERC721(nftAddressArray[i]).safeTransferFrom( from, to, nftTokenIdArray[i] ); else IERC1155(nftAddressArray[i]).safeTransferFrom( from, to, nftTokenIdArray[i], 1, '0x00' ); } /** * @notice Transfer eth or erc20 tokens fron an account to another * @param from From account address. * @param to To account address. * @param currency Address of erc20 token to be transfered, 0x00 for eth. * @param qty1 Amount of tokens to be transfered to relevant party account. * @param qty2 Amount of tokens to be transfered to this contract's author. */ function _transferTokens( address from, address payable to, address currency, uint256 qty1, uint256 qty2 ) internal { if ( currency != address(0) ){ require(IERC20(currency).transferFrom( from, to, qty1 ), "Transfer of tokens to receiver failed"); require(IERC20(currency).transferFrom( from, owner(), qty2 ), "Transfer of tokens to Stater failed"); }else{ require(to.send(qty1), "Transfer of ETH to receiver failed"); require(payable(owner()).send(qty2), "Transfer of ETH to Stater failed"); } } }
Adds a new geyser address to the list geyserAddress The new geyser address/
function addGeyserAddress(address geyserAddress) external onlyOwner { geyserAddressArray.push(geyserAddress); }
1,767,358
/** * @title DVIP Contract. DCAsset Membership Token contract. * * @author Ray Pulver, ray@decentralizedcapital.com */ contract Relay { function relayReceiveApproval(address _caller, address _spender, uint256 _amount, bytes _extraData) returns (bool success); } contract DVIPBackend { uint8 public decimals; function assert(bool assertion) { if (!assertion) throw; } address public owner; event SetOwner(address indexed previousOwner, address indexed newOwner); modifier onlyOwner { assert(msg.sender == owner); _ } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } bool internal locked; event Locked(address indexed from); event PropertySet(address indexed from); modifier onlyIfUnlocked { assert(!locked); _ } modifier setter { _ PropertySet(msg.sender); } modifier onlyOwnerUnlocked { assert(!locked && msg.sender == owner); _ } function lock() onlyOwner onlyIfUnlocked { locked = true; Locked(msg.sender); } function isLocked() returns (bool status) { return locked; } bytes32 public standard = 'Token 0.1'; bytes32 public name; bytes32 public symbol; bool public allowTransactions; uint256 public totalSupply; event Approval(address indexed from, address indexed spender, uint256 amount); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); function () { throw; } uint256 public expiry; uint8 public feeDecimals; mapping (address => uint256) public validAfter; uint256 public mustHoldFor; address public hotwalletAddress; address public frontendAddress; mapping (address => bool) public frozenAccount; mapping (address => uint256) public exportFee; event FeeSetup(address indexed from, address indexed target, uint256 amount); event Processed(address indexed sender); modifier onlyAsset { if (msg.sender != frontendAddress) throw; _ } /** * Constructor. * */ function DVIPBackend(address _hotwalletAddress, address _frontendAddress) { owner = msg.sender; hotwalletAddress = _hotwalletAddress; frontendAddress = _frontendAddress; allowTransactions = true; totalSupply = 0; name = "DVIP"; symbol = "DVIP"; feeDecimals = 6; expiry = 1514764800; //1 jan 2018 mustHoldFor = 86400; } function setHotwallet(address _address) onlyOwnerUnlocked { hotwalletAddress = _address; PropertySet(msg.sender); } function setFrontend(address _address) onlyOwnerUnlocked { frontendAddress = _address; PropertySet(msg.sender); } /** * @notice Transfer `_amount` from `msg.sender.address()` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address caller, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(balanceOf[caller] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(!frozenAccount[caller]); assert(!frozenAccount[_to]); balanceOf[caller] -= _amount; uint256 preBalance = balanceOf[_to]; balanceOf[_to] += _amount; if (preBalance <= 1 && balanceOf[_to] >= 1) { validAfter[_to] = now + mustHoldFor; } Transfer(caller, _to, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address caller, address _from, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(_amount <= allowance[_from][caller]); assert(!frozenAccount[caller]); assert(!frozenAccount[_from]); assert(!frozenAccount[_to]); balanceOf[_from] -= _amount; uint256 preBalance = balanceOf[_to]; balanceOf[_to] += _amount; allowance[_from][caller] -= _amount; if (balanceOf[_to] >= 1 && preBalance <= 1) { validAfter[_to] = now + mustHoldFor; } Transfer(_from, _to, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; Relay(frontendAddress).relayReceiveApproval(caller, _spender, _amount, _extraData); Approval(caller, _spender, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address caller, address _spender, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; Approval(caller, _spender, _amount); return true; } /* --------------- multisig admin methods --------------*/ /** * @notice Sets the expiry time in milliseconds since 1970. * * @param ts milliseconds since 1970. * */ function setExpiry(uint256 ts) onlyOwner { expiry = ts; Processed(msg.sender); } /** * @notice Mints `mintedAmount` new tokens to the hotwallet `hotWalletAddress`. * * @param mintedAmount Amount of new tokens to be minted. */ function mint(uint256 mintedAmount) onlyOwner { balanceOf[hotwalletAddress] += mintedAmount; totalSupply += mintedAmount; Processed(msg.sender); } function freezeAccount(address target, bool frozen) onlyOwner { frozenAccount[target] = frozen; Processed(msg.sender); } function seizeTokens(address target, uint256 amount) onlyOwner { assert(balanceOf[target] >= amount); assert(frozenAccount[target]); balanceOf[target] -= amount; balanceOf[hotwalletAddress] += amount; Transfer(target, hotwalletAddress, amount); } function destroyTokens(uint256 amt) onlyOwner { assert(balanceOf[hotwalletAddress] >= amt); balanceOf[hotwalletAddress] -= amt; Processed(msg.sender); } /** * @notice Sets an export fee of `fee` on address `addr` * * @param addr Address for which the fee is valid * @param addr fee Fee * */ function setExportFee(address addr, uint256 fee) onlyOwner { exportFee[addr] = fee; Processed(msg.sender); } function setHoldingPeriod(uint256 ts) onlyOwner { mustHoldFor = ts; Processed(msg.sender); } function setAllowTransactions(bool allow) onlyOwner { allowTransactions = allow; Processed(msg.sender); } /* --------------- fee calculation method ---------------- */ /** * @notice 'Returns the fee for a transfer from `from` to `to` on an amount `amount`. * * Fee's consist of a possible * - import fee on transfers to an address * - export fee on transfers from an address * DVIP ownership on an address * - reduces fee on a transfer from this address to an import fee-ed address * - reduces the fee on a transfer to this address from an export fee-ed address * DVIP discount does not work for addresses that have an import fee or export fee set up against them. * * DVIP discount goes up to 100% * * @param from From address * @param to To address * @param amount Amount for which fee needs to be calculated. * */ function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value) { uint256 fee = exportFee[from]; if (fee == 0) return 0; if ((exportFee[from] == 0 && balanceOf[from] != 0 && now < expiry && validAfter[from] <= now) || (balanceOf[to] != 0 && now < expiry && validAfter[to] <= now)) return 0; return div10(amount*fee, feeDecimals); } function div10(uint256 a, uint8 b) internal returns (uint256 result) { for (uint8 i = 0; i < b; i++) { a /= 10; } return a; } }
Sets the expiry time in milliseconds since 1970. ts milliseconds since 1970./
function setExpiry(uint256 ts) onlyOwner { expiry = ts; Processed(msg.sender); }
2,512,490
./partial_match/1/0xD22a61e8503Bea5842e5e0126ca9fFC4dd492084/sources/StrawberryElephant.sol
Subtracts two int256 variables and fails on overflow./
function sub(int256 a, int256 b) internal pure returns(int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; }
11,027,054
./partial_match/1/0x5fE4e37c9FC121A602bAcCeaA9CEDeDb6153d3E6/sources/contracts/soma/TemplateFactory/TemplateFactoryLibrary.sol
See {ITemplateFactory-deployTemplate}./
function deployTemplate( ITemplateFactory factory, bytes32 templateId, uint256 version, bytes memory args, bytes[] memory functionCalls ) internal returns (address instance) { return deployTemplate(factory, templateId, version, args, functionCalls, defaultSalt(templateId, version)); }
9,426,623
./full_match/1/0xE8c1B97913cB46BB8741e6FA483717Ea89FfC56d/sources/contracts/TeaVaultV2.sol
Deposit ERC721 tokens Only the investor can do this _token address of the NFT _tokenId the NFT to deposit
function deposit721(address _token, uint256 _tokenId) external nonReentrant onlyInvestor { IERC721(_token).safeTransferFrom(msg.sender, address(this), _tokenId); emit Token721Deposited(msg.sender, _token, _tokenId); }
3,870,436
./full_match/80001/0xD9409a073a6Ca9C6b7f87e001212F7E4C699A192/sources/contracts/NftTokenCrowdsale.sol
Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. _buyer Address receiving the tokens/
function _processPurchase(address _buyer, uint256 _typeId) internal { _deliverTokens(_buyer, _typeId); }
9,485,159
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "../base/Owned.sol"; import "./AuthereumProxy.sol"; contract AuthereumEnsManager { function register(string calldata _label, address _owner) external {} } /** * @title AuthereumProxyFactory * @author Authereum Labs, Inc. * @dev A factory that creates Authereum Proxies. */ contract AuthereumProxyFactory is Owned { string constant public authereumProxyFactoryVersion = "2019111500"; bytes private initCode; address private authereumEnsManagerAddress; AuthereumEnsManager authereumEnsManager; event InitCodeChanged(bytes initCode); event AuthereumEnsManagerChanged(address indexed authereumEnsManager); /// @dev Constructor /// @param _implementation Address of the Authereum implementation /// @param _authereumEnsManagerAddress Address for the Authereum ENS Manager contract constructor(address _implementation, address _authereumEnsManagerAddress) public { initCode = abi.encodePacked(type(AuthereumProxy).creationCode, uint256(_implementation)); authereumEnsManagerAddress = _authereumEnsManagerAddress; authereumEnsManager = AuthereumEnsManager(authereumEnsManagerAddress); emit InitCodeChanged(initCode); emit AuthereumEnsManagerChanged(authereumEnsManagerAddress); } /** * Setters */ /// @dev Setter for the proxy initCode /// @param _initCode Init code off the AuthereumProxy and constructor function setInitCode(bytes memory _initCode) public onlyOwner { initCode = _initCode; emit InitCodeChanged(initCode); } /// @dev Setter for the Authereum ENS Manager address /// @param _authereumEnsManagerAddress Address of the new Authereum ENS Manager function setAuthereumEnsManager(address _authereumEnsManagerAddress) public onlyOwner { authereumEnsManagerAddress = _authereumEnsManagerAddress; authereumEnsManager = AuthereumEnsManager(authereumEnsManagerAddress); emit AuthereumEnsManagerChanged(authereumEnsManagerAddress); } /** * Getters */ /// @dev Getter for the proxy initCode /// @return Init code function getInitCode() public view returns (bytes memory) { return initCode; } /// @dev Getter for the private authereumEnsManager variable /// @return Authereum Ens Manager function getAuthereumEnsManager() public view returns (address) { return authereumEnsManagerAddress; } /// @dev Create an Authereum Proxy and iterate through initialize data /// @notice The bytes[] _initData is an array of initialize functions. /// @notice This is used when a user creates an account e.g. on V5, but V1,2,3, /// @notice etc. have state vars that need to be included. /// @param _salt A uint256 value to add randomness to the account creation /// @param _label Label for the user's Authereum ENS subdomain /// @param _initData Array of initialize data function createProxy( uint256 _salt, string memory _label, bytes[] memory _initData ) public onlyOwner returns (AuthereumProxy) { address payable addr; bytes memory _initCode = initCode; bytes32 salt = _getSalt(_salt, msg.sender); // Create proxy assembly { addr := create2(0, add(_initCode, 0x20), mload(_initCode), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } // Loop through initializations of each version of the logic contract bool success; for (uint256 i = 0; i < _initData.length; i++) { require(_initData[i].length != 0, "APF: Empty initialization data"); (success,) = addr.call(_initData[i]); require(success, "APF: Unsuccessful account initialization"); } // Set ENS name authereumEnsManager.register(_label, addr); return AuthereumProxy(addr); } /// @dev Generate a salt out of a uint256 value and the sender /// @param _salt A uint256 value to add randomness to the account creation /// @param _sender Sender of the transaction function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_salt, _sender)); } }
Create an Authereum Proxy and iterate through initialize data The bytes[] _initData is an array of initialize functions. This is used when a user creates an account e.g. on V5, but V1,2,3, etc. have state vars that need to be included. _salt A uint256 value to add randomness to the account creation _label Label for the user's Authereum ENS subdomain _initData Array of initialize data Create proxy
function createProxy( uint256 _salt, string memory _label, bytes[] memory _initData ) public onlyOwner returns (AuthereumProxy) { address payable addr; bytes memory _initCode = initCode; bytes32 salt = _getSalt(_salt, msg.sender); assembly { addr := create2(0, add(_initCode, 0x20), mload(_initCode), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } for (uint256 i = 0; i < _initData.length; i++) { require(_initData[i].length != 0, "APF: Empty initialization data"); (success,) = addr.call(_initData[i]); require(success, "APF: Unsuccessful account initialization"); } return AuthereumProxy(addr); }
942,640