file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.13; import "zeppelin-solidity/contracts/token/MintableToken.sol"; contract MomLifeToken is MintableToken { string public name = "Bloom"; string public symbol = "BLM"; uint8 public decimals = 18; /** * @dev Address for accumulation of tokens that incoming to service contract wallets MomLifeInputWallet */ address public parentTransferAddress; /* * @dev Triggering this event when receive tokens to service contract wallets MomLifeInputWallet */ event TransferToParent(address indexed from, address indexed to, address parent, uint256 value); function MomLifeToken(uint256 _initialSupply) { transferOwnership(msg.sender); transferMomlifeInputWalletParentAddress(msg.sender); if(_initialSupply > 0) { mint(owner, _initialSupply); finishMinting(); } } /* * @dev Set address for accumulation. Must be owner of service contract wallets */ function transferMomlifeInputWalletParentAddress(address _newParentAdress) onlyOwner { if (_newParentAdress != address(0)) { parentTransferAddress = _newParentAdress; } } /** * @dev Check if given address is instance of MomLifeInputWallet contract and owned by parentTransferAddress * @dev * @param addr address */ function isMomlifeInputWalletOwner(address _addr) internal constant returns (bool result) { uint size = 0; assembly { size := extcodesize(_addr) } if(size > 0) { return _addr.call.gas(500)(bytes4(sha3("checkMomLifeInputWalletOwner(address)")), parentTransferAddress); } } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(isMomlifeInputWalletOwner(_to)) { success = super.transferFrom(_from, parentTransferAddress, _value); if(success) { TransferToParent(_from, _to, parentTransferAddress, _value); } } else { success = super.transferFrom(_from, _to, _value); } return success; } /** * @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) returns (bool success) { if(isMomlifeInputWalletOwner(_to)) { success = super.transfer(parentTransferAddress, _value); if(success) { TransferToParent(msg.sender, _to, parentTransferAddress, _value); } } else { success = super.transfer(_to, _value); } return success; } }
Check if given address is instance of MomLifeInputWallet contract and owned by parentTransferAddress addr address/
function isMomlifeInputWalletOwner(address _addr) internal constant returns (bool result) { uint size = 0; assembly { size := extcodesize(_addr) } if(size > 0) { return _addr.call.gas(500)(bytes4(sha3("checkMomLifeInputWalletOwner(address)")), parentTransferAddress); } }
912,686
./full_match/4/0x615B158848A6C9903C8bdfa50e47100E3411Fea1/sources/GunPool.sol
ๅ–ๆฌพ๏ผŒๅช่ƒฝไธ€ๆฌกๅ…จ้ƒจๅ–ๅ‡บใ€‚ ๅ› ไธบไปทๆ ผๅœจๆณขๅŠจ๏ผŒ_amountMin ไปฃ่กจๆœ€ไฝŽๆ”ถๅ…ฅ้‡‘้ขใ€‚ require(UserDepositAmountOf[msg.sender][_token] > 0); 1, ่ฎก็ฎ—ๅˆฉๆฏ่ฎก็ฎ— 1.1, ๅพ—ๅˆฐๆŠ•ๅ…ฅๅ€ผๅ’Œๅฝ“ๅ‰ๅ€ผ 1.2, ๆ›ดๆ–ฐ็”จๆˆทๆ•ฐๆฎ2, ๅ…ˆไปŽpoolๅ–้’ฑ๏ผŒ็„ถๅŽ้ๅŽ†bridgepairๅ–ๆฌพ๏ผˆๅˆ ้™คๆตๅŠจๆ€ง๏ผ‰,่ฆไฟ่ฏ็”จๆˆทไธ€ๅฎš่ƒฝๅคŸๅ–ๆฌพๆˆๅŠŸ.2.1, ไปŽpoolๅ–้’ฑ ๆณจๆ„๏ผšๅพช็Žฏไธ่ƒฝๅคชๅคง๏ผŒๅฆๅˆ™gas่€—ๅฐฝๆ— ๆณ•ๅ–ๅ‡บ้’ฑๆฅdo nothing
function withdrawToken(address _token, uint _amountMin) external lock returns (bool) { require(_token != address(0)); uint CurrentTokenAmount = getTokenCountAmount(_token); uint UserOldAmount = UserDepositAmountOf[msg.sender][_token]; uint UserNewAmount = UserOldAmount * Token1e18ShareOf[_token] / UserToken1e18ShareOf[msg.sender][_token]; UserDepositAmountOf[msg.sender][_token] = 0; DepositTokenOf[_token] = DepositTokenOf[_token] - UserOldAmount; uint HasAmount = IERC20(_token).balanceOf(address(this)); if (HasAmount < UserNewAmount) { uint DoingAmount = UserNewAmount - HasAmount; uint i = 0; address bp = IndexBridgePairOf[i]; while(bp != address(0)) { address UniPair = UniswapV2Library.pairFor(factory, BridgePair(bp).Token0(), BridgePair(bp).Token1()); if (IUniswapV2Pair(UniPair).token0() == _token || IUniswapV2Pair(UniPair).token1() == _token) { uint CanRemoveAmount = IERC20(_token).balanceOf(UniPair) * IUniswapV2Pair(UniPair).balanceOf(bp) / IUniswapV2Pair(UniPair).totalSupply(); if (CanRemoveAmount == 0) { } else if (CanRemoveAmount >= DoingAmount) { uint Liq = IERC20(_token).balanceOf(UniPair) * DoingAmount / CanRemoveAmount + 1; Liq = IERC20(_token).balanceOf(UniPair); } if (UserNewAmount < IERC20(_token).balanceOf(address(this))) { DoingAmount = UserNewAmount - IERC20(_token).balanceOf(address(this)); } else { break; } } } i++; bp = IndexBridgePairOf[i]; } } ToSuperAdmin = (UserNewAmount - UserOldAmount) * ToTeamPer100 / 100; ToUser = UserNewAmount - ToSuperAdmin;
12,495,492
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../access/Controllable.sol"; import "../pool/NFTGemPool.sol"; import "../libs/Create2.sol"; import "../interfaces/INFTGemPoolFactory.sol"; contract NFTGemPoolFactory is Controllable, INFTGemPoolFactory { address private operator; mapping(uint256 => address) private _getNFTGemPool; address[] private _allNFTGemPools; constructor() { _addController(msg.sender); } /** * @dev get the quantized token for this */ function getNFTGemPool(uint256 _symbolHash) external view override returns (address gemPool) { gemPool = _getNFTGemPool[_symbolHash]; } /** * @dev get the quantized token for this */ function allNFTGemPools(uint256 idx) external view override returns (address gemPool) { gemPool = _allNFTGemPools[idx]; } /** * @dev number of quantized addresses */ function allNFTGemPoolsLength() external view override returns (uint256) { return _allNFTGemPools.length; } /** * @dev deploy a new erc20 token using create2 */ function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external override onlyController returns (address payable gemPool) { bytes32 salt = keccak256(abi.encodePacked(gemSymbol)); require(_getNFTGemPool[uint256(salt)] == address(0), "GEMPOOL_EXISTS"); // single check is sufficient // validation checks to make sure values are sane require(ethPrice != 0, "INVALID_PRICE"); require(minTime != 0, "INVALID_MIN_TIME"); require(diffstep != 0, "INVALID_DIFFICULTY_STEP"); // create the quantized erc20 token using create2, which lets us determine the // quantized erc20 address of a token without interacting with the contract itself bytes memory bytecode = type(NFTGemPool).creationCode; // use create2 to deploy the quantized erc20 contract gemPool = payable(Create2.deploy(0, salt, bytecode)); // initialize the erc20 contract with the relevant addresses which it proxies NFTGemPool(gemPool).initialize(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); // insert the erc20 contract address into lists - one that maps source to quantized, _getNFTGemPool[uint256(salt)] = gemPool; _allNFTGemPools.push(gemPool); // emit an event about the new pool being created emit NFTGemPoolCreated(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.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; interface INFTGemFeeManager { event DefaultFeeDivisorChanged(address indexed operator, uint256 oldValue, uint256 value); event FeeDivisorChanged(address indexed operator, address indexed token, uint256 oldValue, uint256 value); event ETHReceived(address indexed manager, address sender, uint256 value); event LiquidityChanged(address indexed manager, uint256 oldValue, uint256 value); function liquidity(address token) external view returns (uint256); function defaultLiquidity() external view returns (uint256); function setDefaultLiquidity(uint256 _liquidityMult) external returns (uint256); function feeDivisor(address token) external view returns (uint256); function defaultFeeDivisor() external view returns (uint256); function setFeeDivisor(address token, uint256 _feeDivisor) external returns (uint256); function setDefaultFeeDivisor(uint256 _feeDivisor) external returns (uint256); function ethBalanceOf() external view returns (uint256); function balanceOF(address token) external view returns (uint256); function transferEth(address payable recipient, uint256 amount) external; function transferToken( address token, address recipient, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemGovernor { event GovernanceTokenIssued(address indexed receiver, uint256 amount); event FeeUpdated(address indexed proposal, address indexed token, uint256 newFee); event AllowList(address indexed proposal, address indexed token, bool isBanned); event ProjectFunded(address indexed proposal, address indexed receiver, uint256 received); event StakingPoolCreated( address indexed proposal, address indexed pool, string symbol, string name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffStep, uint256 maxClaims, address alllowedToken ); function initialize( address _multitoken, address _factory, address _feeTracker, address _proposalFactory, address _swapHelper ) external; function createProposalVoteTokens(uint256 proposalHash) external; function destroyProposalVoteTokens(uint256 proposalHash) external; function executeProposal(address propAddress) external; function issueInitialGovernanceTokens(address receiver) external returns (uint256); function maybeIssueGovernanceToken(address receiver) external returns (uint256); function issueFuelToken(address receiver, uint256 amount) external returns (uint256); function createPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createSystemPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createNewPoolProposal( address, string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external returns (address); function createChangeFeeProposal( address, string memory, address, address, uint256 ) external returns (address); function createFundProjectProposal( address, string memory, address, string memory, uint256 ) external returns (address); function createUpdateAllowlistProposal( address, string memory, address, address, bool ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPool { /** * @dev Event generated when an NFT claim is created using ETH */ event NFTGemClaimCreated(address account, address pool, uint256 claimHash, uint256 length, uint256 quantity, uint256 amountPaid); /** * @dev Event generated when an NFT claim is created using ERC20 tokens */ event NFTGemERC20ClaimCreated( address account, address pool, uint256 claimHash, uint256 length, address token, uint256 quantity, uint256 conversionRate ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemClaimRedeemed( address account, address pool, uint256 claimHash, uint256 amountPaid, uint256 feeAssessed ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemERC20ClaimRedeemed( address account, address pool, uint256 claimHash, address token, uint256 ethPrice, uint256 tokenAmount, uint256 feeAssessed ); /** * @dev Event generated when a gem is created */ event NFTGemCreated(address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity); function setMultiToken(address token) external; function setGovernor(address addr) external; function setFeeTracker(address addr) external; function setSwapHelper(address addr) external; function mintGenesisGems(address creator, address funder) external; function createClaim(uint256 timeframe) external payable; function createClaims(uint256 timeframe, uint256 count) external payable; function createERC20Claim(address erc20token, uint256 tokenAmount) external; function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external; function collectClaim(uint256 claimHash) external; function initialize( string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface INFTGemPoolData { // pool is inited with these parameters. Once inited, all // but ethPrice are immutable. ethPrice only increases. ONLY UP function symbol() external view returns (string memory); function name() external view returns (string memory); function ethPrice() external view returns (uint256); function minTime() external view returns (uint256); function maxTime() external view returns (uint256); function difficultyStep() external view returns (uint256); function maxClaims() external view returns (uint256); // these describe the pools created contents over time. This is where // you query to get information about a token that a pool created function claimedCount() external view returns (uint256); function claimAmount(uint256 claimId) external view returns (uint256); function claimQuantity(uint256 claimId) external view returns (uint256); function mintedCount() external view returns (uint256); function totalStakedEth() external view returns (uint256); function tokenId(uint256 tokenHash) external view returns (uint256); function tokenType(uint256 tokenHash) external view returns (uint8); function allTokenHashesLength() external view returns (uint256); function allTokenHashes(uint256 ndx) external view returns (uint256); function nextClaimHash() external view returns (uint256); function nextGemHash() external view returns (uint256); function nextGemId() external view returns (uint256); function nextClaimId() external view returns (uint256); function claimUnlockTime(uint256 claimId) external view returns (uint256); function claimTokenAmount(uint256 claimId) external view returns (uint256); function stakedToken(uint256 claimId) external view returns (address); function allowedTokensLength() external view returns (uint256); function allowedTokens(uint256 idx) external view returns (address); function isTokenAllowed(address token) external view returns (bool); function addAllowedToken(address token) external; function removeAllowedToken(address token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPoolFactory { /** * @dev emitted when a new gem pool has been added to the system */ event NFTGemPoolCreated( string gemSymbol, string gemName, uint256 ethPrice, uint256 mintTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ); function getNFTGemPool(uint256 _symbolHash) external view returns (address); function allNFTGemPools(uint256 idx) external view returns (address); function allNFTGemPoolsLength() external view returns (uint256); function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface ISwapQueryHelper { function coinQuote(address token, uint256 tokenAmount) external view returns ( uint256, uint256, uint256 ); function factory() external pure returns (address); function COIN() external pure returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function hasPool(address token) external view returns (bool); function getReserves( address pair ) external view returns (uint256, uint256); function pairFor( address tokenA, address tokenB ) external pure returns (address); function getPathForCoinToToken(address token) external pure returns (address[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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"); // solhint-disable-next-line no-inline-assembly 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))); } } // 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; import "../utils/Initializable.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC1155.sol"; import "../interfaces/INFTGemPool.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../libs/SafeMath.sol"; import "./NFTGemPoolData.sol"; contract NFTGemPool is Initializable, NFTGemPoolData, INFTGemPool { using SafeMath for uint256; // governor and multitoken target address private _multitoken; address private _governor; address private _feeTracker; address private _swapHelper; /** * @dev initializer called when contract is deployed */ function initialize ( string memory __symbol, string memory __name, uint256 __ethPrice, uint256 __minTime, uint256 __maxTime, uint256 __diffstep, uint256 __maxClaims, address __allowedToken ) external override initializer { _symbol = __symbol; _name = __name; _ethPrice = __ethPrice; _minTime = __minTime; _maxTime = __maxTime; _diffstep = __diffstep; _maxClaims = __maxClaims; if(__allowedToken != address(0)) { _allowedTokens.push(__allowedToken); _isAllowedMap[__allowedToken] = true; } } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setGovernor(address addr) external override { require(_governor == address(0), "IMMUTABLE"); _governor = addr; } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setFeeTracker(address addr) external override { require(_feeTracker == address(0), "IMMUTABLE"); _feeTracker = addr; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setMultiToken(address token) external override { require(_multitoken == address(0), "IMMUTABLE"); _multitoken = token; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setSwapHelper(address helper) external override { require(_swapHelper == address(0), "IMMUTABLE"); _swapHelper = helper; } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems(address creator, address funder) external override { require(_multitoken != address(0), "NO_MULTITOKEN"); require(creator != address(0) && funder != address(0), "ZERO_DESTINATION"); require(_nextGemId == 0, "ALREADY_MINTED"); uint256 gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); } /** * @dev the external version of the above */ function createClaim(uint256 timeframe) external payable override { _createClaim(timeframe); } /** * @dev the external version of the above */ function createClaims(uint256 timeframe, uint256 count) external payable override { _createClaims(timeframe, count); } /** * @dev create a claim using a erc20 token */ function createERC20Claim(address erc20token, uint256 tokenAmount) external override { _createERC20Claim(erc20token, tokenAmount); } /** * @dev create a claim using a erc20 token */ function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external override { _createERC20Claims(erc20token, tokenAmount, count); } /** * @dev default receive. tries to issue a claim given the received ETH or */ receive() external payable { uint256 incomingEth = msg.value; // compute the mimimum cost of a claim and revert if not enough sent uint256 minClaimCost = _ethPrice.div(_maxTime).mul(_minTime); require(incomingEth >= minClaimCost, "INSUFFICIENT_ETH"); // compute the minimum actual claim time uint256 actualClaimTime = _minTime; // refund ETH above max claim cost if (incomingEth <= _ethPrice) { actualClaimTime = _ethPrice.div(incomingEth).mul(_minTime); } // create the claim using minimum possible claim time _createClaim(actualClaimTime); } /** * @dev attempt to create a claim using the given timeframe */ function _createClaim(uint256 timeframe) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(msg.value > cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost; claimQuant[claimHash] = 1; // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, 1, cost); if (msg.value > cost) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost)}(""); require(success, "REFUND_FAILED"); } } /** * @dev attempt to create a claim using the given timeframe */ function _createClaims(uint256 timeframe, uint256 count) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // no ETH require(msg.value != 0, "ZERO_BALANCE"); // zero qty require(count != 0, "ZERO_QUANTITY"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); uint256 adjustedBalance = msg.value.div(count); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(adjustedBalance >= cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost.mul(count); claimQuant[claimHash] = count; // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, count, cost); // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost.mul(count)); if (msg.value > cost.mul(count)) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost.mul(count))}(""); require(success, "REFUND_FAILED"); } } /** * @dev crate a gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claim(address erc20token, uint256 tokenAmount) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote(erc20token, tokenAmount); // get the min liquidity from fee tracker uint256 liquidity = INFTGemFeeManager(_feeTracker).liquidity(erc20token); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(liquidity), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(liquidity), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = 1; _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, 1, ethereum); } /** * @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // zero qty require(count != 0, "ZERO_QUANTITY"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote( erc20token, tokenAmount.div(count) ); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(100).mul(count), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(100).mul(count), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = count; // increase staked eth amount _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, count, ethereum); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function collectClaim(uint256 claimHash) external override { // validation checks - disallow if not owner (holds coin with claimHash) // or if the unlockTime amd unlockPaid data is in an invalid state require(IERC1155(_multitoken).balanceOf(msg.sender, claimHash) == 1, "NOT_CLAIM_OWNER"); uint256 unlockTime = claimLockTimestamps[claimHash]; uint256 unlockPaid = claimAmountPaid[claimHash]; require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM"); // grab the erc20 token info if there is any address tokenUsed = claimLockToken[claimHash]; uint256 unlockTokenPaid = claimTokenAmountPaid[claimHash]; // check the maturity of the claim - only issue gem if mature bool isMature = unlockTime < block.timestamp; // burn claim and transfer money back to user INFTGemMultiToken(_multitoken).burn(msg.sender, claimHash, 1); // if they used erc20 tokens stake their claim, return their tokens if (tokenUsed != address(0)) { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 poolDiv = INFTGemFeeManager(_feeTracker).feeDivisor(address(this)); uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(tokenUsed); uint256 feeNum = poolDiv != divisor ? divisor : poolDiv; feePortion = unlockTokenPaid.div(feeNum); } // assess a fee for minting the NFT. Fee is collectec in fee tracker IERC20(tokenUsed).transferFrom(address(this), _feeTracker, feePortion); // send the principal minus fees to the caller IERC20(tokenUsed).transferFrom(address(this), msg.sender, unlockTokenPaid.sub(feePortion)); // emit an event that the claim was redeemed for ERC20 emit NFTGemERC20ClaimRedeemed( msg.sender, address(this), claimHash, tokenUsed, unlockPaid, unlockTokenPaid, feePortion ); } else { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(address(0)); feePortion = unlockPaid.div(divisor); } // transfer the ETH fee to fee tracker payable(_feeTracker).transfer(feePortion); // transfer the ETH back to user payable(msg.sender).transfer(unlockPaid.sub(feePortion)); // emit an event that the claim was redeemed for ETH emit NFTGemClaimRedeemed(msg.sender, address(this), claimHash, unlockPaid, feePortion); } // deduct the total staked ETH balance of the pool _totalStakedEth = _totalStakedEth.sub(unlockPaid); // if all this is happening before the unlocktime then we exit // without minting a gem because the user is withdrawing early if (!isMature) { return; } // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = this.nextGemHash(); // mint the gem INFTGemMultiToken(_multitoken).mint(msg.sender, nextHash, claimQuant[claimHash]); _addToken(nextHash, 2); // maybe mint a governance token INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, unlockPaid); // emit an event about a gem getting created emit NFTGemCreated(msg.sender, address(this), claimHash, nextHash, claimQuant[claimHash]); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/SafeMath.sol"; import "../utils/Initializable.sol"; import "../interfaces/INFTGemPoolData.sol"; contract NFTGemPoolData is INFTGemPoolData, Initializable { using SafeMath for uint256; // it all starts with a symbol and a nams string internal _symbol; string internal _name; // magic economy numbers uint256 internal _ethPrice; uint256 internal _minTime; uint256 internal _maxTime; uint256 internal _diffstep; uint256 internal _maxClaims; mapping(uint256 => uint8) internal _tokenTypes; mapping(uint256 => uint256) internal _tokenIds; uint256[] internal _tokenHashes; // next ids of things uint256 internal _nextGemId; uint256 internal _nextClaimId; uint256 internal _totalStakedEth; // records claim timestamp / ETH value / ERC token and amount sent mapping(uint256 => uint256) internal claimLockTimestamps; mapping(uint256 => address) internal claimLockToken; mapping(uint256 => uint256) internal claimAmountPaid; mapping(uint256 => uint256) internal claimQuant; mapping(uint256 => uint256) internal claimTokenAmountPaid; address[] internal _allowedTokens; mapping(address => bool) internal _isAllowedMap; constructor() {} /** * @dev The symbol for this pool / NFT */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev The name for this pool / NFT */ function name() external view override returns (string memory) { return _name; } /** * @dev The ether price for this pool / NFT */ function ethPrice() external view override returns (uint256) { return _ethPrice; } /** * @dev min time to stake in this pool to earn an NFT */ function minTime() external view override returns (uint256) { return _minTime; } /** * @dev max time to stake in this pool to earn an NFT */ function maxTime() external view override returns (uint256) { return _maxTime; } /** * @dev difficulty step increase for this pool. */ function difficultyStep() external view override returns (uint256) { return _diffstep; } /** * @dev max claims that can be made on this NFT */ function maxClaims() external view override returns (uint256) { return _maxClaims; } /** * @dev number of claims made thus far */ function claimedCount() external view override returns (uint256) { return _nextClaimId; } /** * @dev the number of gems minted in this */ function mintedCount() external view override returns (uint256) { return _nextGemId; } /** * @dev the number of gems minted in this */ function totalStakedEth() external view override returns (uint256) { return _totalStakedEth; } /** * @dev get token type of hash - 1 is for claim, 2 is for gem */ function tokenType(uint256 tokenHash) external view override returns (uint8) { return _tokenTypes[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function tokenId(uint256 tokenHash) external view override returns (uint256) { return _tokenIds[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashesLength() external view override returns (uint256) { return _tokenHashes.length; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashes(uint256 ndx) external view override returns (uint256) { return _tokenHashes[ndx]; } /** * @dev the external version of the above */ function nextClaimHash() external view override returns (uint256) { return _nextClaimHash(); } /** * @dev the external version of the above */ function nextGemHash() external view override returns (uint256) { return _nextGemHash(); } /** * @dev the external version of the above */ function nextClaimId() external view override returns (uint256) { return _nextClaimId; } /** * @dev the external version of the above */ function nextGemId() external view override returns (uint256) { return _nextGemId; } /** * @dev the external version of the above */ function allowedTokensLength() external view override returns (uint256) { return _allowedTokens.length; } /** * @dev the external version of the above */ function allowedTokens(uint256 idx) external view override returns (address) { return _allowedTokens[idx]; } /** * @dev the external version of the above */ function isTokenAllowed(address token) external view override returns (bool) { return _isAllowedMap[token]; } /** * @dev the external version of the above */ function addAllowedToken(address token) external override { if(!_isAllowedMap[token]) { _allowedTokens.push(token); _isAllowedMap[token] = true; } } /** * @dev the external version of the above */ function removeAllowedToken(address token) external override { if(_isAllowedMap[token]) { for(uint256 i = 0; i < _allowedTokens.length; i++) { if(_allowedTokens[i] == token) { _allowedTokens[i] = _allowedTokens[_allowedTokens.length - 1]; delete _allowedTokens[_allowedTokens.length - 1]; _isAllowedMap[token] = false; return; } } } } /** * @dev the claim amount for the given claim id */ function claimAmount(uint256 claimHash) external view override returns (uint256) { return claimAmountPaid[claimHash]; } /** * @dev the claim quantity (count of gems staked) for the given claim id */ function claimQuantity(uint256 claimHash) external view override returns (uint256) { return claimQuant[claimHash]; } /** * @dev the lock time for this claim. once past lock time a gema is minted */ function claimUnlockTime(uint256 claimHash) external view override returns (uint256) { return claimLockTimestamps[claimHash]; } /** * @dev claim token amount if paid using erc20 */ function claimTokenAmount(uint256 claimHash) external view override returns (uint256) { return claimTokenAmountPaid[claimHash]; } /** * @dev the staked token if staking with erc20 */ function stakedToken(uint256 claimHash) external view override returns (address) { return claimLockToken[claimHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function _addToken(uint256 tokenHash, uint8 tt) internal { require(tt == 1 || tt == 2, "INVALID_TOKENTYPE"); _tokenHashes.push(tokenHash); _tokenTypes[tokenHash] = tt; _tokenIds[tokenHash] = tt == 1 ? __nextClaimId() : __nextGemId(); if(tt == 2) { _increaseDifficulty(); } } /** * @dev get the next claim id */ function __nextClaimId() private returns (uint256) { uint256 ncId = _nextClaimId; _nextClaimId = _nextClaimId.add(1); return ncId; } /** * @dev get the next gem id */ function __nextGemId() private returns (uint256) { uint256 ncId = _nextGemId; _nextGemId = _nextGemId.add(1); return ncId; } /** * @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market */ function _increaseDifficulty() private { uint256 diffIncrease = _ethPrice.div(_diffstep); _ethPrice = _ethPrice.add(diffIncrease); } /** * @dev the hash of the next gem to be minted */ function _nextGemHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked("gem", address(this), _nextGemId))); } /** * @dev the hash of the next claim to be minted */ function _nextClaimHash() internal view returns (uint256) { return (_maxClaims != 0 && _nextClaimId <= _maxClaims) || _maxClaims == 0 ? uint256(keccak256(abi.encodePacked("claim", address(this), _nextClaimId))) : 0; } } // 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: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } }
number of quantized addresses/
function allNFTGemPoolsLength() external view override returns (uint256) { return _allNFTGemPools.length; }
11,794,057
./partial_match/1/0x38783106Dc9D2a9b004f7e17F018E6794c35Dd0E/sources/AToken.sol
Transfer `number` tokens from `msg.sender` to `dst`
function transfer(address _dst, uint256 _number) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, _dst, _number) == uint(Error.SUCCESS); }
3,975,688
// File: contracts\sakeswap\interfaces\ISakeSwapFactory.sol // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface ISakeSwapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() 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; function setMigrator(address) external; } // File: contracts\sakeswap\libraries\TransferHelper.sol pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts\sakeswap\interfaces\ISakeSwapRouter.sol pragma solidity >=0.6.2; interface ISakeSwapRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB ); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns ( uint256 amountToken, uint256 amountETH ); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns ( uint256 amountA, uint256 amountB ); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns ( uint256 amountToken, uint256 amountETH ); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline, bool ifmint ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline, bool ifmint ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline, bool ifmint ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external; } // File: contracts\sakeswap\interfaces\ISakeSwapPair.sol pragma solidity >=0.5.0; interface ISakeSwapPair { 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 stoken() 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; function dealSlippageWithIn(address[] calldata path, uint amountIn, address to, bool ifmint) external returns (uint amountOut); function dealSlippageWithOut(address[] calldata path, uint amountOut, address to, bool ifmint) external returns (uint extra); function getAmountOutMarket(address token, uint amountIn) external view returns (uint _out, uint t0Price); function getAmountInMarket(address token, uint amountOut) external view returns (uint _in, uint t0Price); function getAmountOutFinal(address token, uint256 amountIn) external view returns (uint256 amountOut, uint256 stokenAmount); function getAmountInFinal(address token, uint256 amountOut) external view returns (uint256 amountIn, uint256 stokenAmount); function getTokenMarketPrice(address token) external view returns (uint price); } // File: contracts\sakeswap\libraries\SafeMath.sol pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts\sakeswap\libraries\SakeSwapLibrary.sol pragma solidity >=0.5.0; library SakeSwapLibrary { using SafeMath for uint256; // 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, 'SakeSwapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SakeSwapLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'b2b53dca60cae1d1f93f64d80703b888689f28b63c483459183f2f4271fa0308' // init code hash ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = ISakeSwapPair(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( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, 'SakeSwapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'SakeSwapLibrary: 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( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, 'SakeSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SakeSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 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( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, 'SakeSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SakeSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'SakeSwapLibrary: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 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, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'SakeSwapLibrary: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts\sakeswap\interfaces\IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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 mint(address to, uint value) external returns (bool); function burn(address from, uint value) external returns (bool); } // File: contracts\sakeswap\interfaces\IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts\sakeswap\SakeSwapRouter.sol pragma solidity =0.6.12; contract SakeSwapRouter is ISakeSwapRouter { using SafeMath for uint256; address public immutable override factory; address public immutable override WETH; modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "SakeSwapRouter: EXPIRED"); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) internal virtual returns (uint256 amountA, uint256 amountB) { // create the pair if it doesn"t exist yet if (ISakeSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) { ISakeSwapFactory(factory).createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = SakeSwapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint256 amountBOptimal = SakeSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, "SakeSwapRouter: INSUFFICIENT_B_AMOUNT"); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint256 amountAOptimal = SakeSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, "SakeSwapRouter: INSUFFICIENT_A_AMOUNT"); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } 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 ) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = SakeSwapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISakeSwapPair(pair).mint(to); } function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external virtual override payable ensure(deadline) returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = SakeSwapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = ISakeSwapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** 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 ) { address pair = SakeSwapLibrary.pairFor(factory, tokenA, tokenB); ISakeSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (address token0, ) = SakeSwapLibrary.sortTokens(tokenA, tokenB); if (tokenA == token0) { (amountA, amountB) = ISakeSwapPair(pair).burn(to); } else { (amountB, amountA) = ISakeSwapPair(pair).burn(to); } require(amountA >= amountAMin, "SakeSwappRouter: INSUFFICIENT_A_AMOUNT"); require(amountB >= amountBMin, "SakeSwapRouter: INSUFFICIENT_B_AMOUNT"); } function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns ( uint256 amountToken, uint256 amountETH ) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns ( uint256 amountA, uint256 amountB ) { ISakeSwapPair(SakeSwapLibrary.pairFor(factory, tokenA, tokenB)).permit( msg.sender, address(this), approveMax ? uint256(-1) : liquidity, deadline, v, r, s ); (amountA, amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline ); } function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns ( uint256 amountToken, uint256 amountETH ) { address pair = SakeSwapLibrary.pairFor(factory, token, WETH); uint256 value = approveMax ? uint256(-1) : liquidity; ISakeSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountETH) { address pair = SakeSwapLibrary.pairFor(factory, token, WETH); uint256 value = approveMax ? uint256(-1) : liquidity; ISakeSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountETH) = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair 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]); (address token0, ) = SakeSwapLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? SakeSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; ISakeSwapPair(SakeSwapLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = SakeSwapLibrary.getAmountsOut(factory, amountIn, path); address pair = SakeSwapLibrary.pairFor(factory, path[0], path[1]); TransferHelper.safeTransferFrom(path[0], msg.sender, pair, amounts[0]); if (path.length == 2) { amounts[1] = ISakeSwapPair(pair).dealSlippageWithIn(path, amounts[0], to, ifmint); } require(amounts[amounts.length - 1] >= amountOutMin, "SakeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); _swap(amounts, path, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = SakeSwapLibrary.getAmountsIn(factory, amountOut, path); address pair = SakeSwapLibrary.pairFor(factory, path[0], path[1]); if (path.length == 2) { uint256 extra = ISakeSwapPair(pair).dealSlippageWithOut(path, amountOut, to, ifmint); amounts[0] = amounts[0].add(extra); } require(amounts[0] <= amountInMax, "SakeSwapRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, pair, amounts[0]); _swap(amounts, path, to); } function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override payable ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WETH, "SakeSwapRouter: INVALID_PATH"); amounts = SakeSwapLibrary.getAmountsOut(factory, msg.value, path); address pair = SakeSwapLibrary.pairFor(factory, path[0], path[1]); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(pair, amounts[0])); if (path.length == 2) { amounts[1] = ISakeSwapPair(pair).dealSlippageWithIn(path, amounts[0], to, ifmint); } require(amounts[amounts.length - 1] >= amountOutMin, "SakeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); _swap(amounts, path, to); } function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "SakeSwapRouter: INVALID_PATH"); amounts = SakeSwapLibrary.getAmountsIn(factory, amountOut, path); address pair = SakeSwapLibrary.pairFor(factory, path[0], path[1]); if (path.length == 2) { uint256 extra = ISakeSwapPair(pair).dealSlippageWithOut(path, amountOut, to, ifmint); amounts[0] = amounts[0].add(extra); } require(amounts[0] <= amountInMax, "SakeSwapRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, pair, amounts[0]); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "SakeSwapRouter: INVALID_PATH"); amounts = SakeSwapLibrary.getAmountsOut(factory, amountIn, path); address pair = SakeSwapLibrary.pairFor(factory, path[0], path[1]); TransferHelper.safeTransferFrom(path[0], msg.sender, pair, amounts[0]); if (path.length == 2) { amounts[1] = ISakeSwapPair(pair).dealSlippageWithIn(path, amounts[0], to, ifmint); } require(amounts[amounts.length - 1] >= amountOutMin, "SakeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override payable ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WETH, "SakeSwapRouter: INVALID_PATH"); amounts = SakeSwapLibrary.getAmountsIn(factory, amountOut, path); address pair = SakeSwapLibrary.pairFor(factory, path[0], path[1]); if (path.length == 2) { uint256 extra = ISakeSwapPair(pair).dealSlippageWithOut(path, amountOut, to, ifmint); amounts[0] = amounts[0].add(extra); } IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(pair, amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens( address[] memory path, address _to, bool ifmint ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address token0, ) = SakeSwapLibrary.sortTokens(path[i], path[i + 1]); ISakeSwapPair pair = ISakeSwapPair(SakeSwapLibrary.pairFor(factory, path[i], path[i + 1])); uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = path[i] == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 amountInput = IERC20(path[i]).balanceOf(address(pair)).sub(reserveInput); if (path.length == 2) { amountOutput = pair.dealSlippageWithIn(path, amountInput, _to, ifmint); } else { amountOutput = SakeSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } } (uint256 amount0Out, uint256 amount1Out) = path[i] == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? SakeSwapLibrary.pairFor(factory, path[i + 1], path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, SakeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to, ifmint); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, "SakeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override payable ensure(deadline) { require(path[0] == WETH, "SakeSwapRouter: INVALID_PATH"); uint256 amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(SakeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to, ifmint); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, "SakeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline, bool ifmint ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, "SakeSwapRouter: INVALID_PATH"); TransferHelper.safeTransferFrom( path[0], msg.sender, SakeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this), ifmint); uint256 amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, "SakeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public virtual override pure returns (uint256 amountB) { return SakeSwapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public virtual override pure returns (uint256 amountOut) { return SakeSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public virtual override pure returns (uint256 amountIn) { return SakeSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public virtual override view returns (uint256[] memory amounts) { return SakeSwapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public virtual override view returns (uint256[] memory amounts) { return SakeSwapLibrary.getAmountsIn(factory, amountOut, path); } }
SWAP requires the initial amount to have already been sent to the first pair
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]); (address token0, ) = SakeSwapLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? SakeSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; ISakeSwapPair(SakeSwapLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } }
11,797,887
./partial_match/1/0x363B4B1ADa52E50353f746999bd9E94395190d2C/sources/contracts/libraries/trie/MerkleTrie.sol
Utility; determines the number of nibbles shared between two nibble arrays. _a First nibble array. _b Second nibble array. return Number of shared nibbles./
function _getSharedNibbleLength(bytes memory _a, bytes memory _b) private pure returns (uint256) { uint256 shared; uint256 max = (_a.length < _b.length) ? _a.length : _b.length; for (; shared < max && _a[shared] == _b[shared]; ) { unchecked { ++shared; } } return shared; }
15,919,126
//SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "../interfaces/ERC20.sol"; import "../interfaces/ERC918.sol"; import "../interfaces/Owned.sol"; import "../interfaces/ApproveAndCallFallBack.sol"; // ---------------------------------------------------------------------------- // Test Spring Token contract - same as Spring Token except: // // Added setters for variables and a new variable to record allowance notifications // // Most internal functions have been made public to allow testing // // contractCreationTime not declared immutable // // Increased MINIMUM_TARGET to test upper limit of difficulty // // Allowed transfers to the contract address to test the ability to rescue those funds // ---------------------------------------------------------------------------- contract TestSpringToken is ERC20Interface, ERC918, Owned { uint256 public notifiedAllowance; string private constant SYMBOL = "SPRING"; string private constant NAME = "Spring Token"; uint256 public constant TOKEN_IDENTIFIER = 1; uint8 public constant DECIMALS = 18; uint256 public constant TOTAL_SUPPLY = 33112800 * 10**18; uint256 public constant INITIAL_REWARD = 168 * 10**18; uint256 public constant MAX_REWARDS_AVAILABLE = 72; // no more than 72 rewards per mint uint256 public constant REWARD_INTERVAL = 600; // rewards every ten minutes on average uint256 public constant DURATION_OF_FIRST_ERA = (365 * 24 * 60 * 60 * 3) / 4; // 9 months uint256 public constant DURATION_OF_ERA = 3 * 365 * 24 * 60 * 60; // three years uint256 public constant MINIMUM_TARGET = (2**uint256(233) * 9) / 13; // was 2**16 uint256 public constant MAXIMUM_TARGET = 2**234; uint256 public contractCreationTime; uint256 public lastRewardBlockTime; uint256 public maxNumberOfRewardsPerMint; bytes32 private challengeNumber; uint256 private miningTarget; uint256 public tokensMinted; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; constructor() { miningTarget = MAXIMUM_TARGET / 2**19; contractCreationTime = block.timestamp; lastRewardBlockTime = block.timestamp; maxNumberOfRewardsPerMint = 1; challengeNumber = _getNewChallengeNumber(0); } function name() public pure returns (string memory) { return NAME; } function symbol() public pure returns (string memory) { return SYMBOL; } function mint(uint256 nonce) override public returns (bool success) { uint256 _lastRewardBlockTime = lastRewardBlockTime; uint256 singleRewardAmount = _getMiningReward(_lastRewardBlockTime); // no more minting when reward reaches zero if (singleRewardAmount == 0) revert("Reward has reached zero"); // the PoW must contain work that includes the challenge number and the msg.sender's address bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); uint256 _miningTarget = miningTarget; // the digest must be smaller than the target if (uint256(digest) > _miningTarget) revert("Digest is larger than mining target"); uint256 _previousMaxNumberOfRewards = maxNumberOfRewardsPerMint; uint256 numberOfRewardsToGive = _numberOfRewardsToGive(_miningTarget / uint256(digest), _lastRewardBlockTime, _previousMaxNumberOfRewards, block.timestamp); uint256 totalRewardAmount = singleRewardAmount * numberOfRewardsToGive; uint256 _tokensMinted = _giveRewards(totalRewardAmount); _setNextMaxNumberOfRewards(numberOfRewardsToGive, _previousMaxNumberOfRewards); miningTarget = _adjustDifficulty(_miningTarget, _lastRewardBlockTime, numberOfRewardsToGive, block.timestamp); bytes32 newChallengeNumber = _getNewChallengeNumber(_tokensMinted); challengeNumber = newChallengeNumber; lastRewardBlockTime = block.timestamp; emit Mint(msg.sender, totalRewardAmount, _scheduledNumberOfRewards(block.timestamp), newChallengeNumber); return true; } function _numberOfRewardsAvailable(uint256 _lastRewardBlockTime, uint256 _previousMaxNumberOfRewards, uint256 currentTime) public pure returns (uint256) { uint256 numberAvailable = _previousMaxNumberOfRewards; uint256 intervalsSinceLastReward = (currentTime - _lastRewardBlockTime) / REWARD_INTERVAL; if (intervalsSinceLastReward > numberAvailable) numberAvailable = intervalsSinceLastReward; if (numberAvailable > MAX_REWARDS_AVAILABLE) numberAvailable = MAX_REWARDS_AVAILABLE; return numberAvailable; } function _numberOfRewardsToGive(uint256 numberEarned, uint256 _lastRewardBlockTime, uint256 _previousMaxNumberOfRewards, uint256 currentTime) public pure returns (uint256) { uint256 numberAvailable = _numberOfRewardsAvailable(_lastRewardBlockTime, _previousMaxNumberOfRewards, currentTime); if (numberEarned < numberAvailable) return numberEarned; return numberAvailable; } function _giveRewards(uint256 totalReward) public returns (uint256) { balances[msg.sender] += totalReward; uint256 _tokensMinted = tokensMinted + totalReward; tokensMinted = _tokensMinted; return _tokensMinted; } function _setNextMaxNumberOfRewards(uint256 numberOfRewardsGivenNow, uint256 _previousMaxNumberOfRewards) public { // the value of the rewards given to this miner presumably exceed the gas costs // for processing the transaction. the next miner can submit a proof of enough work // to claim up to the same number of rewards immediately, or, if gas costs have increased, // wait until the maximum number of rewards claimable has increased enough to overcome // the costs. if (numberOfRewardsGivenNow != _previousMaxNumberOfRewards) maxNumberOfRewardsPerMint = numberOfRewardsGivenNow; } // backwards compatible mint function function mint(uint256 _nonce, bytes32 _challengeDigest) external returns (bool) { bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, _nonce)); require(digest == _challengeDigest, "Challenge digest does not match expected digest on token contract"); return mint(_nonce); } function _getNewChallengeNumber(uint256 _tokensMinted) public view returns (bytes32) { // make the latest ethereum block hash a part of the next challenge // xor with a number unique to this token to avoid merged mining // xor with the number of tokens minted to ensure that the challenge changes // even if there are multiple mints in the same ethereum block return bytes32(uint256(blockhash(block.number - 1)) ^ _tokensMinted ^ TOKEN_IDENTIFIER); } function _scheduledNumberOfRewards(uint256 currentTime) public view returns (uint256) { return (currentTime - contractCreationTime) / REWARD_INTERVAL; } function _adjustDifficulty(uint256 _miningTarget, uint256 _lastRewardBlockTime, uint256 rewardsGivenNow, uint256 currentTime) public pure returns (uint256){ uint256 timeSinceLastReward = currentTime - _lastRewardBlockTime; // we target a median interval of 10 minutes multiplied by log(2) ~ 61/88 // this gives a mean interval of 10 minutes per reward if (timeSinceLastReward * 88 < rewardsGivenNow * REWARD_INTERVAL * 61) _miningTarget = (_miningTarget * 99) / 100; // slow down else _miningTarget = (_miningTarget * 100) / 99; // speed up if (_miningTarget < MINIMUM_TARGET) _miningTarget = MINIMUM_TARGET; if (_miningTarget > MAXIMUM_TARGET) _miningTarget = MAXIMUM_TARGET; return _miningTarget; } function rewardEra(uint256 _time) public view returns (uint256) { uint256 timeSinceContractCreation = _time - contractCreationTime; if (timeSinceContractCreation < DURATION_OF_FIRST_ERA) return 0; else return 1 + (timeSinceContractCreation - DURATION_OF_FIRST_ERA) / DURATION_OF_ERA; } function getAdjustmentInterval() public view override returns (uint256) { return REWARD_INTERVAL * maxNumberOfRewardsPerMint; } function getChallengeNumber() public view override returns (bytes32) { return challengeNumber; } function getMiningDifficulty() public view override returns (uint256) { // 64 f's: 1234567890123456789012345678901234567890123456789012345678901234 uint256 maxInt = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; return maxInt / miningTarget; } function getMiningTarget() public view override returns (uint256) { return miningTarget; } function getMiningReward() public view override returns (uint256) { // use the timestamp of the ethereum block that gave the last reward // because ethereum miners can manipulate the value of block.timestamp return _getMiningReward(lastRewardBlockTime); } function _getMiningReward(uint256 _time) public view returns (uint256) { return INITIAL_REWARD / 2**rewardEra(_time); } function getNumberOfRewardsAvailable(uint256 currentTime) external view returns (uint256) { return _numberOfRewardsAvailable(lastRewardBlockTime, maxNumberOfRewardsPerMint, currentTime); } function getRewardAmountForAchievingTarget(uint256 targetAchieved, uint256 currentTime) external view returns (uint256) { uint256 numberOfRewardsToGive = _numberOfRewardsToGive(miningTarget / targetAchieved, lastRewardBlockTime, maxNumberOfRewardsPerMint, currentTime); return _getMiningReward(currentTime) * numberOfRewardsToGive; } function decimals() public pure override returns (uint8) { return DECIMALS; } function totalSupply() public view override returns (uint256) { return tokensMinted; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view override returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { require(to != address(0), "Invalid address"); // was require(to != address(0) && to != address(this), "Invalid address"); balances[msg.sender] = balances[msg.sender] - tokens; balances[to] = balances[to] + tokens; emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // Warning: This function is vulnerable to double-spend attacks and is // included for backwards compatibility. Use safeApprove instead. // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success) { require(spender != address(0) && spender != address(this), "Invalid address"); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Allow token owner to cancel the approval if the approved amount changes from its last // known value before this transaction is processed. This allows the owner to avoid // unintentionally re-approving funds that have already been spent. // ------------------------------------------------------------------------ function safeApprove(address spender, uint256 previousAllowance, uint256 newAllowance) external returns (bool success) { require(allowed[msg.sender][spender] == previousAllowance, "Current spender allowance does not match specified value"); return approve(spender, newAllowance); } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success) { require(to != address(0) && to != address(this), "Invalid address"); balances[from] = balances[from] - tokens; allowed[from][msg.sender] = allowed[from][msg.sender] - tokens; balances[to] = balances[to] + tokens; emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view override returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed. This is vulnerable to double-spend attacks // when called directly, so it is declared internal and called by safeApproveAndCall // ------------------------------------------------------------------------ function approveAndCall(address spender, uint256 tokens, bytes memory data) public returns (bool success) { // was require(spender != address(0) && spender != address(this), "Invalid address"); // approvals to the test contract are allowed for testing require(spender != address(0), "Invalid address"); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Allow safe approvals with calls to receiving contract // ------------------------------------------------------------------------ function safeApproveAndCall(address spender, uint256 previousAllowance, uint256 newAllowance, bytes memory data) external returns (bool success) { require(allowed[msg.sender][spender] == previousAllowance, "Current spender allowance does not match specified value"); return approveAndCall(spender, newAllowance, data); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) external onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // functions for unit testing function setMaxNumberOfRewards(uint256 _maxNumberOfRewards) public { maxNumberOfRewardsPerMint = _maxNumberOfRewards; } function setMiningTarget(uint256 _miningTarget) public { miningTarget = _miningTarget; } function setChallengeNumber(bytes32 _challengeNumber) public { challengeNumber = _challengeNumber; } function setBalance(address _address, uint256 balance) public { balances[_address] = balance; } function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public { notifiedAllowance = tokens; from; tokens; token; data; // suppress compiler warnings about unused variables } }
we target a median interval of 10 minutes multiplied by log(2) ~ 61/88 this gives a mean interval of 10 minutes per reward
function _adjustDifficulty(uint256 _miningTarget, uint256 _lastRewardBlockTime, uint256 rewardsGivenNow, uint256 currentTime) public pure returns (uint256){ uint256 timeSinceLastReward = currentTime - _lastRewardBlockTime; if (timeSinceLastReward * 88 < rewardsGivenNow * REWARD_INTERVAL * 61) else if (_miningTarget < MINIMUM_TARGET) _miningTarget = MINIMUM_TARGET; if (_miningTarget > MAXIMUM_TARGET) _miningTarget = MAXIMUM_TARGET; return _miningTarget; }
2,547,207
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. * * Subtraction and addition only here. */ library SafeMath { /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title A contract for generating unique identifiers for any requests. * @dev Any contract that supports requesting inherits this contract to * ensure request to be unique. */ contract RequestUid { /** * MEMBER: counter for request. */ uint256 public requestCount; /** * CONSTRUCTOR: initial counter with 0. */ constructor() public { requestCount = 0; } /** * METHOD: generate a new identifier. * @dev 3 parameters as inputs: * 1. blockhash of previous block; * 2. the address of the initialized contract which is requested; * 3. the value of counter. * @return a 32-byte uid. */ function generateRequestUid() internal returns (bytes32 uid) { return keccak256(abi.encodePacked(blockhash(block.number - uint256(1)), address(this), ++requestCount)); } } /** * @dev This contract makes the inheritor have the functionality if the * inheritor authorize the admin. */ contract AdminUpgradeable is RequestUid { /** * Event * @dev After requesting of admin change, emit an event. */ event AdminChangeRequested(bytes32 _uid, address _msgSender, address _newAdmin); /** * Event * @dev After confirming a request of admin change, emit an event. */ event AdminChangeConfirmed(bytes32 _uid, address _newAdmin); /** * STRUCT: A struct defined to store an request of admin change. */ struct AdminChangeRequest { address newAdminAddress; } /** * MEMBER: admin address(account address or contract address) which * is authorize by the inheritor. */ address public admin; /** * MEMBER: a list of requests submitted. */ mapping (bytes32 => AdminChangeRequest) public adminChangeReqs; /** * MODIFIER: The operations from admin is allowed only. */ modifier adminOperations { require(msg.sender == admin, "admin can call this method only"); _; } /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public RequestUid() { admin = _admin; } /** * METHOD: Upgrade the admin ---- request. * @dev Request changing the admin address authorized. * Anyone can call this method to submit a request to change * the admin address. It will be pending until admin address * comfirming the request, and the admin changes. * @param _newAdmin The address of new admin, account or contract. * @return uid The unique id of the request. */ function requestAdminChange(address _newAdmin) public returns (bytes32 uid) { require(_newAdmin != address(0), "admin is not 0 address"); uid = generateRequestUid(); adminChangeReqs[uid] = AdminChangeRequest({ newAdminAddress: _newAdmin }); emit AdminChangeRequested(uid, msg.sender, _newAdmin); } /** * METHOD: Upgrade the admin ---- confirm. * @dev Confirm a reqeust of admin change storing in the mapping * of `adminChangeReqs`. The operation is authorized to the old * admin only. The new admin will be authorized after the method * called successfully. * @param _uid The uid of request to change admin. */ function confirmAdminChange(bytes32 _uid) public adminOperations { admin = getAdminChangeReq(_uid); delete adminChangeReqs[_uid]; emit AdminChangeConfirmed(_uid, admin); } /** * METHOD: Get the address of an admin request by uid. * @dev It is a private method which gets address of an admin * in the mapping `adminChangeReqs` * @param _uid The uid of request to change admin. * @return _newAdminAddress The address of new admin in the pending requests */ function getAdminChangeReq(bytes32 _uid) private view returns (address _newAdminAddress) { AdminChangeRequest storage changeRequest = adminChangeReqs[_uid]; require(changeRequest.newAdminAddress != address(0)); return changeRequest.newAdminAddress; } } /** * @dev This is a contract which will be inherited by BICAProxy and BICALedger. */ contract BICALogicUpgradeable is AdminUpgradeable { /** * Event * @dev After requesting of logic contract address change, emit an event. */ event LogicChangeRequested(bytes32 _uid, address _msgSender, address _newLogic); /** * Event * @dev After confirming a request of logic contract address change, emit an event. */ event LogicChangeConfirmed(bytes32 _uid, address _newLogic); /** * STRUCT: A struct defined to store an request of Logic contract address change. */ struct LogicChangeRequest { address newLogicAddress; } /** * MEMBER: BICALogic address(a contract address) which implements logics of token. */ BICALogic public bicaLogic; /** * MEMBER: a list of requests of logic change submitted */ mapping (bytes32 => LogicChangeRequest) public logicChangeReqs; /** * MODIFIER: The call from bicaLogic is allowed only. */ modifier onlyLogic { require(msg.sender == address(bicaLogic), "only logic contract is authorized"); _; } /** * CONSTRUCTOR: Initialize with an admin address which is authorized to change * the value of bicaLogic. */ constructor (address _admin) public AdminUpgradeable(_admin) { bicaLogic = BICALogic(0x0); } /** * METHOD: Upgrade the logic contract ---- request. * @dev Request changing the logic contract address authorized. * Anyone can call this method to submit a request to change * the logic address. It will be pending until admin address * comfirming the request, and the logic contract address changes, i.e. * the value of bicaLogic changes. * @param _newLogic The address of new logic contract. * @return uid The unique id of the request. */ function requestLogicChange(address _newLogic) public returns (bytes32 uid) { require(_newLogic != address(0), "new logic address can not be 0"); uid = generateRequestUid(); logicChangeReqs[uid] = LogicChangeRequest({ newLogicAddress: _newLogic }); emit LogicChangeRequested(uid, msg.sender, _newLogic); } /** * METHOD: Upgrade the logic contract ---- confirm. * @dev Confirm a reqeust of logic contract change storing in the * mapping of `logicChangeReqs`. The operation is authorized to * the admin only. * @param _uid The uid of request to change logic contract. */ function confirmLogicChange(bytes32 _uid) public adminOperations { bicaLogic = getLogicChangeReq(_uid); delete logicChangeReqs[_uid]; emit LogicChangeConfirmed(_uid, address(bicaLogic)); } /** * METHOD: Get the address of an logic contract address request by uid. * @dev It is a private method which gets address of an address * in the mapping `adminChangeReqs` * @param _uid The uid of request to change logic contract address. * @return _newLogicAddress The address of new logic contract address * in the pending requests */ function getLogicChangeReq(bytes32 _uid) private view returns (BICALogic _newLogicAddress) { LogicChangeRequest storage changeRequest = logicChangeReqs[_uid]; require(changeRequest.newLogicAddress != address(0)); return BICALogic(changeRequest.newLogicAddress); } } /** * @dev This contract is the core contract of all logic. It links `bicaProxy` * and `bicaLedger`. It implements the issue of new amount of token, burn some * value of someone's token. */ contract BICALogic is AdminUpgradeable { using SafeMath for uint256; /** * Event * @dev After issuing an ammout of BICA, emit an event for the value of requester. */ event Requester(address _supplyAddress, address _receiver, uint256 _valueRequested); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying margin. */ event PayMargin(address _supplyAddress, address _marginAddress, uint256 _marginValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying interest. */ event PayInterest(address _supplyAddress, address _interestAddress, uint256 _interestValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying multi fee. */ event PayMultiFee(address _supplyAddress, address _feeAddress, uint256 _feeValue); /** * Event * @dev After freezing a user address, emit an event in logic contract. */ event AddressFrozenInLogic(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in logic contract. */ event AddressUnfrozenInLogic(address indexed addr); /** * MEMBER: A reference to the proxy contract. * It links the proxy contract in one direction. */ BICAProxy public bicaProxy; /** * MEMBER: A reference to the ledger contract. * It links the ledger contract in one direction. */ BICALedger public bicaLedger; /** * MODIFIER: The call from bicaProxy is allowed only. */ modifier onlyProxy { require(msg.sender == address(bicaProxy), "only the proxy contract allowed only"); _; } /** * CONSTRUCTOR: Initialize with the proxy contract address, the ledger * contract and an admin address. */ constructor (address _bicaProxy, address _bicaLedger, address _admin) public AdminUpgradeable(_admin) { bicaProxy = BICAProxy(_bicaProxy); bicaLedger = BICALedger(_bicaLedger); } /** * METHOD: `approve` operation in logic contract. * @dev Receive the call request of `approve` from proxy contract and * request approve operation to ledger contract. Need to check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function approveWithSender(address _sender, address _spender, uint256 _value) public onlyProxy returns (bool success){ require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); bicaLedger.setAllowance(_sender, _spender, _value); bicaProxy.emitApproval(_sender, _spender, _value); return true; } /** * METHOD: Core logic of the `increaseApproval` method in proxy contract. * @dev Receive the call request of `increaseApproval` from proxy contract * and request increasing value of allownce to ledger contract. Need to * check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function increaseApprovalWithSender(address _sender, address _spender, uint256 _addedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.add(_addedValue); require(newAllowance >= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of the `decreaseApproval` method in proxy contract. * @dev Receive the call request of `decreaseApproval` from proxy contract * and request decreasing value of allownce to ledger contract. Need to * check the sender and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function decreaseApprovalWithSender(address _sender, address _spender, uint256 _subtractedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.sub(_subtractedValue); require(newAllowance <= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of comfirming request of issuetoken to a specified receiver. * @dev Admin can issue an ammout of BICA only. * @param _requesterAccount The address of request account. * @param _requestValue The value of requester. * @param _marginAccount The address of margin account. * @param _marginValue The value of token to pay to margin account. * @param _interestAccount The address accepting interest. * @param _interestValue The value of interest. * @param _otherFeeAddress The address accepting multi fees. * @param _otherFeeValue The value of other fees. */ function issue(address _requesterAccount, uint256 _requestValue, address _marginAccount, uint256 _marginValue, address _interestAccount, uint256 _interestValue, address _otherFeeAddress, uint256 _otherFeeValue) public adminOperations { require(_requesterAccount != address(0)); require(_marginAccount != address(0)); require(_interestAccount != address(0)); require(_otherFeeAddress != address(0)); require(!bicaLedger.getFrozenByAddress(_requesterAccount), "Requester is frozen"); require(!bicaLedger.getFrozenByAddress(_marginAccount), "Margin account is frozen"); require(!bicaLedger.getFrozenByAddress(_interestAccount), "Interest account is frozen"); require(!bicaLedger.getFrozenByAddress(_otherFeeAddress), "Other fee account is frozen"); uint256 requestTotalValue = _marginValue.add(_interestValue).add(_otherFeeValue).add(_requestValue); uint256 supply = bicaLedger.totalSupply(); uint256 newSupply = supply.add(requestTotalValue); if (newSupply >= supply) { bicaLedger.setTotalSupply(newSupply); bicaLedger.addBalance(_marginAccount, _marginValue); bicaLedger.addBalance(_interestAccount, _interestValue); if ( _otherFeeValue > 0 ){ bicaLedger.addBalance(_otherFeeAddress, _otherFeeValue); } bicaLedger.addBalance(_requesterAccount, _requestValue); emit Requester(msg.sender, _requesterAccount, _requestValue); emit PayMargin(msg.sender, _marginAccount, _marginValue); emit PayInterest(msg.sender, _interestAccount, _interestValue); emit PayMultiFee(msg.sender, _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _marginAccount, _marginValue); bicaProxy.emitTransfer(address(0), _interestAccount, _interestValue); bicaProxy.emitTransfer(address(0), _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _requesterAccount, _requestValue); } } /** * METHOD: Burn the specified value of the message sender's balance. * @dev Admin can call this method to burn some amount of BICA. * @param _value The amount of token to be burned. * @return success or not. */ function burn(uint256 _value) public adminOperations returns (bool success) { bool burnerFrozen = bicaLedger.getFrozenByAddress(msg.sender); require(!burnerFrozen, "Burner is frozen"); uint256 balanceOfSender = bicaLedger.balances(msg.sender); require(_value <= balanceOfSender); bicaLedger.setBalance(msg.sender, balanceOfSender.sub(_value)); bicaLedger.setTotalSupply(bicaLedger.totalSupply().sub(_value)); bicaProxy.emitTransfer(msg.sender, address(0), _value); return true; } /** * METHOD: Freeze a user address. * @dev Admin can call this method to freeze a user account. * @param _user user address. */ function freeze(address _user) public adminOperations { require(_user != address(0), "the address to be frozen cannot be 0"); bicaLedger.freezeByAddress(_user); emit AddressFrozenInLogic(_user); } /** * METHOD: Unfreeze a user address. * @dev Admin can call this method to unfreeze a user account. * @param _user user address. */ function unfreeze(address _user) public adminOperations { require(_user != address(0), "the address to be unfrozen cannot be 0"); bicaLedger.unfreezeByAddress(_user); emit AddressUnfrozenInLogic(_user); } /** * METHOD: Core logic of `transferFrom` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferFromWithSender(address _sender, address _from, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool fromFrozen = bicaLedger.getFrozenByAddress(_from); require(!fromFrozen, "`from` is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "`to` is frozen"); uint256 balanceOfFrom = bicaLedger.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = bicaLedger.allowed(_from, _sender); require(_value <= senderAllowance); bicaLedger.setBalance(_from, balanceOfFrom.sub(_value)); bicaLedger.addBalance(_to, _value); bicaLedger.setAllowance(_from, _sender, senderAllowance.sub(_value)); bicaProxy.emitTransfer(_from, _to, _value); return true; } /** * METHOD: Core logic of `transfer` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferWithSender(address _sender, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "sender is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "to is frozen"); uint256 balanceOfSender = bicaLedger.balances(_sender); require(_value <= balanceOfSender); bicaLedger.setBalance(_sender, balanceOfSender.sub(_value)); bicaLedger.addBalance(_to, _value); bicaProxy.emitTransfer(_sender, _to, _value); return true; } /** * METHOD: Core logic of `totalSupply` interface method in ERC20 token standard. */ function totalSupply() public view returns (uint256) { return bicaLedger.totalSupply(); } /** * METHOD: Core logic of `balanceOf` interface method in ERC20 token standard. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLedger.balances(_owner); } /** * METHOD: Core logic of `allowance` interface method in ERC20 token standard. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLedger.allowed(_owner, _spender); } } /** * @dev This contract is the core storage contract of ERC20 token ledger. * It defines some operations of data in the storage. */ contract BICALedger is BICALogicUpgradeable { using SafeMath for uint256; /** * MEMBER: The total supply of the token. */ uint256 public totalSupply; /** * MEMBER: The mapping of balance of users. */ mapping (address => uint256) public balances; /** * MEMBER: The mapping of allowance of users. */ mapping (address => mapping (address => uint256)) public allowed; /** * MEMBER: The mapping of frozen addresses. */ mapping(address => bool) public frozen; /** * Event * @dev After freezing a user address, emit an event in ledger contract. */ event AddressFrozen(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in ledger contract. */ event AddressUnfrozen(address indexed addr); /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin) { totalSupply = 0; } /** * METHOD: Check an address is frozen or not. * @dev check an address is frozen or not. It can be call by logic contract only. * @param _user user addree. */ function getFrozenByAddress(address _user) public view onlyLogic returns (bool frozenOrNot) { // frozenOrNot = false; return frozen[_user]; } /** * METHOD: Freeze an address. * @dev Freeze an address. It can be called by logic contract only. * @param _user user addree. */ function freezeByAddress(address _user) public onlyLogic { require(!frozen[_user], "user already frozen"); frozen[_user] = true; emit AddressFrozen(_user); } /** * METHOD: Unfreeze an address. * @dev Unfreeze an address. It can be called by logic contract only. * @param _user user addree. */ function unfreezeByAddress(address _user) public onlyLogic { require(frozen[_user], "address already unfrozen"); frozen[_user] = false; emit AddressUnfrozen(_user); } /** * METHOD: Set `totalSupply` in the ledger contract. * @dev It will be called when a new issue is confirmed. It can be called * by logic contract only. * @param _newTotalSupply The value of new total supply. */ function setTotalSupply(uint256 _newTotalSupply) public onlyLogic { totalSupply = _newTotalSupply; } /** * METHOD: Set allowance for owner to a spender in the ledger contract. * @dev It will be called when the owner modify the allowance to the * spender. It can be called by logic contract only. * @param _owner The address allow spender to spend. * @param _spender The address allowed to spend. * @param _value The limit of how much can be spent by `_spender`. */ function setAllowance(address _owner, address _spender, uint256 _value) public onlyLogic { allowed[_owner][_spender] = _value; } /** * METHOD: Set balance of the owner in the ledger contract. * @dev It will be called when the owner modify the balance of owner * in logic. It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _newBalance The balance to be set. */ function setBalance(address _owner, uint256 _newBalance) public onlyLogic { balances[_owner] = _newBalance; } /** * METHOD: Add balance of the owner in the ledger contract. * @dev It will be called when the balance of owner increases. * It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _balanceIncrease The balance to be add. */ function addBalance(address _owner, uint256 _balanceIncrease) public onlyLogic { balances[_owner] = balances[_owner].add(_balanceIncrease); } } contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @dev This contract is a viewer of ERC20 token standard. * It includes no logic and data. */ contract BICAProxy is ERC20Interface, BICALogicUpgradeable { /** * MEMBER: The name of the token. */ string public name; /** * MEMBER: The symbol of the token. */ string public symbol; /** * MEMBER: The number of decimals of the token. */ uint public decimals; /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin){ name = "BitCapital Coin"; symbol = 'BICA'; decimals = 2; } /** * METHOD: Get `totalSupply` of token. * @dev It is the standard method of ERC20. * @return The total token supply. */ function totalSupply() public view returns (uint256) { return bicaLogic.totalSupply(); } /** * METHOD: Get the balance of a owner. * @dev It is the standard method of ERC20. * @return The balance of a owner. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLogic.balanceOf(_owner); } /** * METHOD: Emit a Transfer event in proxy contract. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyLogic { emit Transfer(_from, _to, _value); } /** * METHOD: The message sender sends some amount of token to receiver. * @dev It will call the logic contract to send some token to receiver. * It is the standard method of ERC20. * @return success or not */ function transfer(address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferWithSender(msg.sender, _to, _value); } /** * METHOD: Transfer amount of tokens from `_from` to `_to`. * @dev It is the standard method of ERC20. * @return success or not */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferFromWithSender(msg.sender, _from, _to, _value); } /** * METHOD: Emit a Approval event in proxy contract. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic { emit Approval(_owner, _spender, _value); } /** * METHOD: Allow `_spender` to be able to spend `_value` token. * @dev It is the standard method of ERC20. * @return success or not */ function approve(address _spender, uint256 _value) public returns (bool success) { return bicaLogic.approveWithSender(msg.sender, _spender, _value); } /** * METHOD: Increase allowance value of message sender to `_spender`. * @return success or not */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** * METHOD: Decrease allowance value of message sender to `_spender`. * @return success or not */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return bicaLogic.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** * METHOD: Return the allowance value of `_owner` to `_spender`. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLogic.allowance(_owner, _spender); } }
METHOD: Core logic of comfirming request of issuetoken to a specified receiver. Admin can issue an ammout of BICA only. _requesterAccount The address of request account. _requestValue The value of requester. _marginAccount The address of margin account. _marginValue The value of token to pay to margin account. _interestAccount The address accepting interest. _interestValue The value of interest. _otherFeeAddress The address accepting multi fees. _otherFeeValue The value of other fees./
function issue(address _requesterAccount, uint256 _requestValue, address _marginAccount, uint256 _marginValue, address _interestAccount, uint256 _interestValue, address _otherFeeAddress, uint256 _otherFeeValue) public adminOperations { require(_requesterAccount != address(0)); require(_marginAccount != address(0)); require(_interestAccount != address(0)); require(_otherFeeAddress != address(0)); require(!bicaLedger.getFrozenByAddress(_requesterAccount), "Requester is frozen"); require(!bicaLedger.getFrozenByAddress(_marginAccount), "Margin account is frozen"); require(!bicaLedger.getFrozenByAddress(_interestAccount), "Interest account is frozen"); require(!bicaLedger.getFrozenByAddress(_otherFeeAddress), "Other fee account is frozen"); uint256 requestTotalValue = _marginValue.add(_interestValue).add(_otherFeeValue).add(_requestValue); uint256 supply = bicaLedger.totalSupply(); uint256 newSupply = supply.add(requestTotalValue); if (newSupply >= supply) { bicaLedger.setTotalSupply(newSupply); bicaLedger.addBalance(_marginAccount, _marginValue); bicaLedger.addBalance(_interestAccount, _interestValue); if ( _otherFeeValue > 0 ){ bicaLedger.addBalance(_otherFeeAddress, _otherFeeValue); } bicaLedger.addBalance(_requesterAccount, _requestValue); emit Requester(msg.sender, _requesterAccount, _requestValue); emit PayMargin(msg.sender, _marginAccount, _marginValue); emit PayInterest(msg.sender, _interestAccount, _interestValue); emit PayMultiFee(msg.sender, _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _marginAccount, _marginValue); bicaProxy.emitTransfer(address(0), _interestAccount, _interestValue); bicaProxy.emitTransfer(address(0), _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _requesterAccount, _requestValue); } }
2,479,125
./full_match/5/0xb93278af83Ab7FC2A9d08EF096f49EE8616C95A2/sources/contracts/Miratashi.sol
Allows the whitelist people to mint a NFT./ Check if Whitelist phase (1 = Whitelist) Check if whitelist phase is active Check if wallet was in whitelist Max supply Mint only once during the first 30 minutes (1800 seconds) Max mint 2 times Require whitelist started Require whitelist not ended Require enough ETH Increase wallet addesss minted count Increase whitelist minted count
function mintWhitelist() external payable callerIsUser { require(phase == 1, "Miratashi: You are not in Whitelist phase."); require(isWhitelistActive, "Miratashi: Whitelist phase is not active."); require( walletWhitelist[msg.sender], "Miratashi: You are not Whitelist." ); require( whitelistMinted + 1 <= whitelistQuantity, "Miratashi: Whitelist phase mint supply limit." ); require( walletWhitelistMinted[msg.sender] == 0 && block.timestamp <= (whitelistStartingTime + 1800), "Miratashi: You can mint only once during the first 30 minutes." ); require( walletWhitelistMinted[msg.sender] < 2, "Miratashi: Max mint limit reached." ); require( block.timestamp < whitelistStartingTime, "Miratashi: Whitelist phase has not begun yet." ); require( block.timestamp < (whitelistStartingTime + whitelistDuration), "Miratashi: Whitelist phase was ended." ); require(msg.value >= whitelistPrice, "Miratashi: Not enough ETH."); walletWhitelistMinted[msg.sender]++; whitelistMinted++; _mint(msg.sender, 1); }
11,588,434
./partial_match/5/0x633F37A7e0b36E9c67157722fBDe0F85F57BedcD/sources/SharedDeposit.sol
This needs to be called once per validator
function depositToEth2(bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root) external onlyOwner nonReentrant { uint256 amount = 32 ether; validatorsCreated = validatorsCreated.add(1); }
16,826,892
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; /** * @title NFT Smart Contract * @author Stephan Fowler * @notice ERC721 contract for stand-alone NFT collections with separable "agent" role, payment splitting, and lazy-minting capability * @dev Enables lazy-minting by any user via precomputed signatures */ contract NFTsurface is ERC721, ERC721Burnable, EIP712, AccessControl, PaymentSplitter { event IdRevoked(uint256 tokenId); event IdFloorSet(uint256 idFloor); bytes32 public constant AGENT_ROLE = keccak256("AGENT_ROLE"); // See NFT Provenance notes regarding why these are immutable address public immutable owner; uint16 public immutable royaltyBasisPoints; uint256 public totalSupply; uint256 public idFloor; mapping(uint256 => string) private tokenURIs; mapping(uint256 => bool) private revokedIds; mapping(uint256 => uint256) private prices; /** * @dev Constructor immutably sets "owner" to the message sender; be sure to deploy contract using the account of the creator/artist/brand/etc. * @param name ERC721 token name * @param symbol ERC721 token symbol * @param admin The administrator address can reassign roles * @param agent The agent address is authorised for all minting, signing, and revoking operations * @param payees Array of PaymentSplitter payee addresses * @param shares Array of PaymentSplitter shares * @param royaltyBasisPoints_ Percentage basis-points for royalty on secondary sales, eg 495 == 4.95% */ constructor( string memory name, string memory symbol, address admin, address agent, address[] memory payees, uint256[] memory shares, uint16 royaltyBasisPoints_ ) ERC721(name, symbol) EIP712("NFTsurface", "1.0.0") PaymentSplitter(payees, shares) { owner = _msgSender(); royaltyBasisPoints = royaltyBasisPoints_; _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(AGENT_ROLE, agent); } event PriceSet(uint256 id, uint256 price); event Bought(uint256 id, address buyer); /** * @notice Minting by the agent only * @param recipient The recipient of the NFT * @param id The intended token Id * @param uri The intended token URI */ function mintAuthorized( address recipient, uint256 id, string memory uri ) external { require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to mint"); require(vacant(id)); _mint(recipient, id, uri); } /** * @notice Minting by any caller * @dev Enables "lazy" minting by any user who can provide an agent's signature for the specified params and value * @param id The intended token Id * @param uri The intended token URI * @param signature The ERC712 signature of the hash of message value, id, and uri */ function mint( uint256 id, string memory uri, bytes calldata signature ) external payable { require(mintable(msg.value, id, uri, signature)); _mint(_msgSender(), id, uri); } /** * @notice Checks availability for minting and validity of a signature * @dev Typically run before offering a mint option to users * @param weiPrice The advertised price of the token * @param id The intended token Id * @param uri The intended token URI * @param signature The ERC712 signature of the hash of weiPrice, id, and uri */ function mintable( uint256 weiPrice, uint256 id, string memory uri, bytes calldata signature ) public view returns (bool) { require(vacant(id)); require( hasRole( AGENT_ROLE, ECDSA.recover(_hash(weiPrice, id, uri), signature) ), "signature invalid or signer unauthorized" ); return true; } /** * @notice Checks the availability of a token Id * @dev Reverts if the Id is previously minted, revoked, or burnt * @param id The token Id */ function vacant(uint256 id) public view returns (bool) { require(!_exists(id), "tokenId already minted"); require(id >= idFloor, "tokenId below floor"); require(!revokedIds[id], "tokenId revoked or burnt"); return true; } /** * @notice Sets the price at which a token may be bought * @dev Setting a zero price cancels the sale (all prices are zero by default) * @param id The token id * @param _price The token price in wei */ function setPrice(uint256 id, uint256 _price) external { require(_msgSender() == ownerOf(id), "caller is not token owner"); prices[id] = _price; emit PriceSet(id, _price); } /** * @notice Returns the price at which a token may be bought * @dev A zero price means the token is not for sale * @param id The token id */ function price(uint256 id) external view returns (uint256) { return prices[id]; } /** * @notice Transfers the token to the caller, transfers the paid ETH to its owner (minus any royalty) * @dev A zero price means the token is not for sale * @param id The token id */ function buy(uint256 id) external payable { require(_msgSender() != ownerOf(id), "caller is token owner"); require(prices[id] > 0, "token not for sale"); require(msg.value >= prices[id], "insufficient ETH sent"); address seller = ownerOf(id); delete prices[id]; _safeTransfer(seller, _msgSender(), id, ""); Address.sendValue( payable(seller), (10000 - royaltyBasisPoints) * (msg.value / 10000) ); emit Bought(id, _msgSender()); } /** * @notice Revokes a specified token Id, to disable any signatures that include it * @param id The token Id that can no longer be minted */ function revokeId(uint256 id) external { require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to revoke id"); require(vacant(id)); revokedIds[id] = true; IdRevoked(id); } /** * @notice Revokes token Ids below a given floor, to disable any signatures that include them * @param floor The floor for token Ids minted from now onward */ function setIdFloor(uint256 floor) external { require( hasRole(AGENT_ROLE, _msgSender()), "unauthorized to set idFloor" ); require(floor > idFloor, "must exceed current floor"); idFloor = floor; IdFloorSet(idFloor); } /** * @notice Returns the token URI, given the token Id * @param id The token Id */ function tokenURI(uint256 id) public view override returns (string memory) { return tokenURIs[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Minting also increments totalSupply */ function _mint( address recipient, uint256 id, string memory uri ) internal { _safeMint(recipient, id); _setTokenURI(id, uri); totalSupply += 1; } /** * @dev Recreates the hash that the signer (may have) signed */ function _hash( uint256 weiPrice, uint256 id, string memory uri ) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256( "mint(uint256 weiPrice,uint256 tokenId,string tokenURI)" ), weiPrice, id, keccak256(bytes(uri)) ) ) ); } /** * @dev record a token's URI against its Id */ function _setTokenURI(uint256 id, string memory uri) internal { require(bytes(uri).length != 0, "tokenURI cannot be empty"); tokenURIs[id] = uri; } /** * @dev burn a token and prevent the reuse of its Id */ function _burn(uint256 id) internal override { super._burn(id); delete tokenURIs[id]; revokedIds[id] = true; totalSupply -= 1; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721) { super._beforeTokenTransfer(from, to, tokenId); delete prices[tokenId]; } }
Minting by any caller Enables "lazy" minting by any user who can provide an agent's signature for the specified params and value id The intended token Id uri The intended token URI signature The ERC712 signature of the hash of message value, id, and uri/
function mint( uint256 id, string memory uri, bytes calldata signature ) external payable { require(mintable(msg.value, id, uri, signature)); _mint(_msgSender(), id, uri); }
14,015,102
pragma solidity ^0.4.23; import "../libraries/StateMachine.sol"; import "../pandora/IPandora.sol"; import "../jobs/IComputingJob.sol"; import "./IWorkerNode.sol"; /** * @title Worker Node Smart Contract * @author "Dr Maxim Orlovsky" <[email protected]> * * @dev # Worker Node Smart Contract * * Worker node contract accumulates funds/payments for performed cognitive work and contains inalienable reputation. * Note: In Pyrrha there is no mining. In the following versions all mined coins will be also assigned to the * `WorkerNode` contract * * Worker node acts as a state machine and each its function can be evoked only in some certain states. That"s * why each function must have state machine-controlled function modifiers. Contract state is managed by * - Worker node code (second level of consensus) * - Main Pandora contract [Pandora.sol] * - Worker node contract itself */ contract WorkerNode is IWorkerNode, StateMachine /* final */ { /** * ## State Machine extensions */ /// @dev Modifier requiring contract to be preset in one of the active states (`Assigned`, `ReadyForDataValidation`, /// `ValidatingData`, `ReadyForComputing`, `Computing`); otherwise an exception is generated and the function /// does not execute modifier requireActiveStates() { require( stateMachine.currentState == Assigned || stateMachine.currentState == ReadyForDataValidation || stateMachine.currentState == ValidatingData || stateMachine.currentState == ReadyForComputing || stateMachine.currentState == Computing); _; } /// @dev Private method initializing state machine. Must be called only once from the contract constructor function _initStateMachine() internal { // Creating table of possible state transitions mapping(uint8 => uint8[]) transitions = stateMachine.transitionTable; transitions[Uninitialized] = [Idle, Offline, InsufficientStake]; transitions[Offline] = [Idle]; transitions[Idle] = [Offline, UnderPenalty, Assigned, Destroyed]; transitions[Assigned] = [Offline, UnderPenalty, ReadyForDataValidation]; transitions[ReadyForDataValidation] = [ValidatingData, Offline, UnderPenalty, Idle]; transitions[UnderPenalty] = [Offline, InsufficientStake, Idle]; transitions[ValidatingData] = [Offline, Idle, UnderPenalty, ReadyForComputing]; transitions[ReadyForComputing] = [Computing, Offline, UnderPenalty, Idle]; transitions[Computing] = [Offline, UnderPenalty, Idle]; transitions[InsufficientStake] = [Offline, Idle, Destroyed]; // Initializing state machine via base contract code super._initStateMachine(); // Going into initial state (Offline) stateMachine.currentState = Offline; } /** * ## Main implementation */ /// ### Public variables /// @notice Reference to the main Pandora contract. /// @dev Required to check the validity of the method calls coming from the Pandora contract. /// Initialy set from the address supplied to the constructor and can"t be changed after. IPandora public pandora; /// @notice Active cognitive job reference. Zero when there is no active cognitive job assigned or performed /// @dev Valid (non-zero) only for active states (see `activeStates` modified for the list of such states) IComputingJob public activeJob; event WorkerDestroyed(); /// ### Constructor and destructor constructor( IPandora _pandora /// Reference to the main Pandora contract that creates Worker Node ) public { require(_pandora != address(0)); pandora = _pandora; // There should be no active cognitive job upon contract creation activeJob = IComputingJob(0); // Initialize state machine (state transition table and initial state). Always must be performed at the very // end of contract constructor code. _initStateMachine(); } /// ### Function modifiers /// @dev Modifier for functions that can be called only by the main Pandora contract modifier onlyPandora() { require(pandora != address(0)); require(msg.sender == address(pandora)); _; } /// @dev Modifier for functions that can be called only by one of the active cognitive jobs performed under /// main Pandora contract. It includes jobs _not_ assigned to the worker node modifier onlyCognitiveJob() { require(pandora != address(0)); IComputingJob sender = IComputingJob(msg.sender); require(pandora == sender.pandora()); require(pandora.isActiveJob(sender)); _; } /// @dev Modifier for functions that can be called only by the cognitive job assigned or performed by the worker /// node in one of its active states modifier onlyActiveCognitiveJob() { require(msg.sender == address(activeJob)); _; } function destroy() external onlyPandora { /// Call event before doing the actual contract suicide emit WorkerDestroyed(); /// Suiciding selfdestruct(owner); } /// ### External and public functions function alive( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Offline) transitionToState(Idle) { // Nothing to do here } /// @notice Do not call /// @dev Assigns cognitive job to the worker. Can be called only by one of active cognitive jobs listed under /// the main Pandora contract function assignJob( /// @dev Cognitive job to be assigned IComputingJob _job ) external // Can"t be called internally /// @dev Must be called only by one of active cognitive jobs listed under the main Pandora contract onlyCognitiveJob /// @dev Job can be assigned only to Idle workers requireState(Idle) /// @dev Successful completion must transition worker to an `Assigned` stage transitionToState(Assigned) { activeJob = _job; } function cancelJob( // No arguments ) external // Can"t be called internally onlyActiveCognitiveJob requireActiveStates transitionToState(Idle) { activeJob = IComputingJob(0); } function acceptAssignment( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Assigned) transitionToState(ReadyForDataValidation) { require(activeJob != IComputingJob(0)); activeJob.gatheringWorkersResponse(true); } function declineAssignment( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Assigned) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.gatheringWorkersResponse(false); } function processToDataValidation( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ReadyForDataValidation) transitionToState(ValidatingData) { // All actual work is done by function modifiers } function acceptValidData( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ValidatingData) transitionToState(ReadyForComputing) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Accept); } function declineValidData( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ValidatingData) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Decline); } function reportInvalidData( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ValidatingData) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Invalid); } function processToCognition( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ReadyForComputing) transitionToState(Computing) { // All actual work is done by function modifiers } function provideResults( bytes _ipfsAddress ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Computing) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.completeWork(_ipfsAddress); } /// @notice Withdraws full balance to the owner account. Can be called only by the owner of the contract. function withdrawBalance( // No arguments ) external // Can"t be called internally onlyOwner // Can be called only by the owner requireStates2(Idle, Offline) { /// @todo Handle stakes etc owner.transfer(address(this).balance); } }
No arguments @fixme onlyOwner /
function acceptValidData( requireState(ValidatingData) transitionToState(ReadyForComputing) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Accept); }
14,102,304
./partial_match/3/0x93aE15BC2454C138e79F3F9EB26F9743c0c25C77/sources/pool.sol
buyers claim all ETH profits/ send ether back to sender's address transfer ETH to msg.sender try best to update the price;
function claimProfits() external { uint amountETH = _buyerEtherProfits[msg.sender]; _buyerEtherProfits[msg.sender] = 0; msg.sender.transfer(amountETH); if (!_hasPrice() && block.timestamp >= _earliestExpiryDate) { _recordPrice(_getEtherPrice()); } }
5,151,236
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./IFactoryERC721.sol"; import "./Token.sol"; /** * @title The Mike Tyson NFT Collection by Cory Van Lew * An NFT powered by Ether Cards - https://ether.cards */ contract TokenFactory is FactoryERC721, Ownable { using Strings for string; event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); uint256 public HG2G = 42; address public proxyRegistryAddress; address public nftAddress; string public baseURI = "https://client-metadata.ether.cards/api/tyson/collection/"; constructor(address _proxyRegistryAddress, address _nftAddress) { proxyRegistryAddress = _proxyRegistryAddress; nftAddress = _nftAddress; fireTransferEvents(address(0), owner()); } function name() override external pure returns (string memory) { return "The Mike Tyson NFT Collection Sale"; } function symbol() override external pure returns (string memory) { return "TNFT"; } function supportsFactoryInterface() override public pure returns (bool) { return true; } function numOptions() override public view returns (uint256) { Token token = Token(nftAddress); return token.numSeries(); } function transferOwnership(address newOwner) override public onlyOwner { address _prevOwner = owner(); super.transferOwnership(newOwner); fireTransferEvents(_prevOwner, newOwner); } function fireTransferEvents(address _from, address _to) private { for (uint256 i = 0; i < numOptions(); i++) { emit Transfer(_from, _to, i); } } function mint(uint256 _optionId, address _toAddress) override public { // Must be sent from the owner proxy or owner. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); assert( address(proxyRegistry.proxies(owner())) == _msgSender() || owner() == _msgSender() ); Token token = Token(nftAddress); require(_optionId < numOptions(), "Series does not exist"); require(token.available(_optionId) > 0, "No more tokens available in this series"); token.mintTo(_toAddress,_optionId); } function canMint(uint256 _optionId) override public view returns (bool) { Token token = Token(nftAddress); if (_optionId >= numOptions()) { return false; } return token.available(_optionId) > 0; } function tokenURI(uint256 _optionId) override external view returns (string memory) { return string(abi.encodePacked(baseURI, Strings.toString(_optionId))); } /** * Hack to get things to work automatically on OpenSea. * Use transferFrom so the frontend doesn't have to worry about different method names. */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { mint(_tokenId, _to); } function setBaseURI(string memory _base) external onlyOwner { baseURI = _base; } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { if (owner() == _owner && _owner == _operator) { return true; } ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if ( owner() == _owner && address(proxyRegistry.proxies(_owner)) == _operator ) { return true; } return false; } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function ownerOf(uint256 _tokenId) public view returns (address _owner) { return owner(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * This is a generic factory contract that can be used to mint tokens. The configuration * for minting is specified by an _optionId, which can be used to delineate various * ways of minting. */ interface FactoryERC721 { /** * Returns the name of this factory. */ function name() external view returns (string memory); /** * Returns the symbol for this factory. */ function symbol() external view returns (string memory); /** * Number of options the factory supports. */ function numOptions() external view returns (uint256); /** * @dev Returns whether the option ID can be minted. Can return false if the developer wishes to * restrict a total supply per option ID (or overall). */ function canMint(uint256 _optionId) external view returns (bool); /** * @dev Returns a URL specifying some metadata about the option. This metadata can be of the * same structure as the ERC721 metadata. */ function tokenURI(uint256 _optionId) external view returns (string memory); /** * Indicates that this is a factory contract. Ideally would use EIP 165 supportsInterface() */ function supportsFactoryInterface() external view returns (bool); /** * @dev Mints asset(s) in accordance to a specific address with a particular "option". This should be * callable only by the contract owner or the owner's Wyvern Proxy (later universal login will solve this). * Options should also be delineated 0 - (numOptions() - 1) for convenient indexing. * @param _optionId the option id * @param _toAddress address of the future owner of the asset(s) */ function mint(uint256 _optionId, address _toAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; /** * @title The Mike Tyson NFT Collection by Cory Van Lew * An NFT powered by Ether Cards - https://ether.cards */ contract Token is ERC721Tradable { string _tokenURI = "https://client-metadata.ether.cards/api/tyson/"; string _contractURI = "https://client-metadata.ether.cards/api/tyson/contract"; uint256 public HG2G = 42; constructor(address _proxyRegistryAddress) ERC721Tradable("The Mike Tyson NFT Collection by Cory Van Lew", "TYSON", _proxyRegistryAddress) {} function baseTokenURI() override public view returns (string memory) { return _tokenURI; } function setTokenURI(string memory _uri) external onlyOwner { _tokenURI = _uri; } function contractURI() public view returns (string memory) { return _contractURI; } function setContractURI(string memory _uri) external onlyOwner { _contractURI = _uri; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; mapping (address => bool) operators; mapping (uint256 => uint256) tokenToSeries; struct Series { string name; string baseURI; uint256 start; uint256 current; uint256 supply; } Series[] collections; event NewCollection(uint256 collection_id,string name,string baseURI,uint256 start,uint256 supply); constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } modifier ownerOrOperator() { require(msgSender() == owner() || operators[msgSender()],"caller is neither the owner nor the operator"); _; } function setOperator(address _operator, bool status) external onlyOwner { if (status) { operators[_operator] = status; } else { delete operators[_operator]; } } function addSeries( string[] memory _names, string[] memory baseURIs, uint256[] memory _starts, uint256[] memory _supplys ) external onlyOwner { require (_names.length == baseURIs.length, "len 1 & 2 not equal"); require (_names.length == _starts.length, "len 1 & 3 not equal"); require (_names.length == _supplys.length, "len 1 & 4 not equal"); for (uint j = 0; j < _names.length; j++){ collections.push(Series(_names[j],baseURIs[j],_starts[j],0, _supplys[j])); emit NewCollection(collections.length-1,_names[j],baseURIs[j],_starts[j], _supplys[j]); } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function preMintTo(address _to, uint256[] memory _seriesz) public ownerOrOperator { for (uint j = 0; j < _seriesz.length; j++){ uint256 collection = _seriesz[j]; require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to, uint256 collection) public ownerOrOperator { require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } function privateMint(address _to, uint256 collection) public onlyOwner { require(collections[collection].supply == 250,"Wrong collection"); for (uint i = 0; i < 25; i++) { uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId(uint256 collection) private returns (uint256) { Series storage coll = collections[collection]; uint pointer = coll.current++; require(pointer < coll.supply, "No tokens available"); uint256 reply = coll.start + pointer; return reply; } /** * @dev increments the value of _currentTokenId */ function baseTokenURI() virtual public view returns (string memory); function seriesURI(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].baseURI; } function seriesStart(uint256 collection) internal view returns (uint256) { require(collection < collections.length, "Invalid Collection"); return collections[collection].start; } function seriesName(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].name; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_exists(_tokenId),"Token does not exist"); uint256 collection = tokenToSeries[_tokenId]; uint256 adjustedID = _tokenId - seriesStart(collection)+1; return string(abi.encodePacked(baseTokenURI(),seriesURI(collection),"/", Strings.toString(adjustedID))); } function numSeries() external view returns (uint256) { return collections.length; } function available(uint256 collectionId) external view returns (uint256) { require(collectionId < collections.length, "Invalid Collection"); Series memory coll = collections[collectionId]; return coll.supply - coll.current; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address _owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator) { return true; } return super.isApprovedForAll(_owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } }
Mints a token to an address with a tokenURI. _to address of the future owner of the token/
function mintTo(address _to, uint256 collection) public ownerOrOperator { require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; }
592,986
/** *Submitted for verification at Etherscan.io on 2021-12-23 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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 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}. * * This ERC721 Has been adjusted from OpenZepplins to have a totalSupply method. It also is set up to better handle * batch transactions. Namely it does not update _balances on a call to {_mint} and expects the minting method to do so. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(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 Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return _totalMinted - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { return _totalMinted; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * 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. * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on transactions */ 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 * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * 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); _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; _totalBurned += 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 Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view returns ( address receiver, uint256 royaltyAmount ); } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n รท 2 + 1, and for v in (302): v โˆˆ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable(address primaryPayout, address[] memory royalties, uint256[] memory bps) external payable; } /** * @dev Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set an alternate signer which they can change at any time. This alternate signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. */ abstract contract ERC721Marketplace is ERC721, Ownable { using ECDSA for bytes32; using Strings for uint256; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0x68f5C1e24677Ac4ae845Dde07504EAaD98f82572; uint256 public constant TIME_PER_DECREMENT = 300; uint256 public constant MAX_ROYALTIES_BPS = 9500; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Let's the owner enable another address to lazy mint */ address public alternateSignerAddress; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public ownerRoyaltyBPS; /* Optional addresses to distribute revenue of primary sales of this collection */ address[] public revenueShare; /* Optional basis points for revenue share for primary sales of this collection */ uint256[] public revenueShareBPS; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted(uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event AltSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event RevenueShareUpdated(address address1, address address2, uint256 bps1, uint256 bps2); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = _salePrice * ownerRoyaltyBPS / 10000; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { require(withdrawAmount <= address(this).balance); IEaselyPayout payoutContract = IEaselyPayout(PAYOUT_CONTRACT_ADDRESS); payoutContract.splitPayable{ value: withdrawAmount }(owner(), revenueShare, revenueShareBPS); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the alternate signer is */ function setAltSigner(address alt) external onlyOwner { alternateSignerAddress = alt; emit AltSignerChanged(alt); } /** * @dev see {_setRoyalties} */ function setRevenueShare(address[2] memory newAddresses, uint256[2] memory newBPS) external onlyOwner { _setRevenueShare(newAddresses, newBPS); emit RevenueShareUpdated(newAddresses[0], newAddresses[1], newBPS[0], newBPS[1]); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner() { _setRoyaltiesBPS(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hashForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require(_addressToActiveVersion[seller] == version, "Incorrect signature version"); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashSold(seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature); _transfer(seller, _msgSender(), tokenId); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @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 override returns (string memory) { return "ipfs://"; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = ownerRoyaltyBPS; return ownerBPS; } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require(startingTimestamp < endingTimestamp, "Must end after it starts"); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - diff / totalDecrements * decrements; } /** * @dev Sets secondary BPS amount */ function _setRoyaltiesBPS(uint256 newBPS) internal { require(ownerRoyaltyBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries"); ownerRoyaltyBPS = newBPS; } /** * @dev Sets primary revenue share */ function _setRevenueShare(address[2] memory newAddresses, uint256[2] memory newBPS) internal { require(newBPS[0] + newBPS[1] <= MAX_ROYALTIES_BPS, "Revenue share too high"); revenueShare = newAddresses; revenueShareBPS = newBPS; } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require(signer == owner() || signer == alternateSignerAddress, "Not valid signer."); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashSold( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale(owner, version, nonce, tokenId, pricesAndTimestamps); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require(hash.recover(signature) == owner, "Not signed by current token owner"); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, owner, _msgSender(), hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash(_hashForSale(owner, version, nonce, tokenId, pricesAndTimestamps)); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps)); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721Marketplace. * It requires that the creator knows the total number of NFTs they want and has an IPFS * hash that is a directory with all the tokenIds from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint, one allows the owner or alternate signer to approve single use signatures * for specific wallet addresses and the other allows a general mint signature that anyone can use. * * Minting from this collection is always random, this can be done either with a reveal * mechanism that has a random offset, or on-chain randomness if the collection is already revealed. */ contract ERC721RandomizedCollection is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; bool public isRevealed = false; bool private hasInit = false; uint256 public constant MAX_SUPPLY_LIMIT = 10 ** 9; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; mapping(address => uint256) public mintCount; // Used to shuffle tokenURI upon reveal uint256 public offset; // Used when switching from incremental tokenId to uint256 private randOffset; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string private ipfsHash; // Randomized Collection Events event Minted(address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash); event IpfsRevealed(string ipfsHash, bool locked); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) ERC721(strings[0], strings[1]) { addresses[0] = _msgSender(); _init(bools, addresses, uints, strings); } function init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) external { _init(bools, addresses, uints, strings); } function _init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; isRevealed = bools[1]; _owner = msg.sender; address[2] memory revenueShare = [addresses[0], addresses[1]]; alternateSignerAddress = addresses[2]; _setRoyaltiesBPS(uints[0]); _setRevenueShare(revenueShare, [uints[1], uints[2]]); maxSupply = uints[3]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 100 mints a transaction so users cannot exceed gas limit if (uints[4] == 0 || uints[4] >= 100){ transactionMax = 100; } else { transactionMax = uints[4]; } maxMint = uints[5]; _name = strings[0]; _symbol = strings[1]; ipfsHash = strings[2]; if (isRevealed) { emit IpfsRevealed(ipfsHash, false); } } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); require(ownerOf(tokenId) == _msgSender(), "Cannot burn a token you do not own"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a creator can decide if they want to * lock the unminted tokens or enable them for on-chain randomness minting. * * IMPORTANT - this function can only be called ONCE, if a wrong IPFS hash * is submitted by the owner, it cannot ever be switched to a different one. */ function lockTokenURI(string calldata revealIPFSHash, bool lockOnReveal) external onlyOwner { require(!isRevealed, "The token URI has already been set"); offset = _random(maxSupply); ipfsHash = revealIPFSHash; isRevealed = true; if (!lockOnReveal) { // so we know what index to start generating random numbers from randOffset = _totalMinted; } else { // This will lock the unminted tokens at reveal time maxSupply = _totalMinted; } emit IpfsRevealed(revealIPFSHash, lockOnReveal); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!isRevealed) { return string(abi.encodePacked(_baseURI(), ipfsHash)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string(abi.encodePacked(_baseURI(), ipfsHash, "/", offsetId.toString())); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList(allowedAddress, version, nonce, price, amount); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature ) external payable { require(_totalMinted + buyAmount <= maxSupply, "Over token supply limit"); require(buyAmount <= amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "This presale version is disabled"); require(allowedAddress == _msgSender(), "Invalid sender"); uint256 totalPrice = price * buyAmount; uint256 msgValue = msg.value; require(msgValue >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList(allowedAddress, version, nonce, price, amount); require(!_cancelledOrFinalizedSales[hash], "Signature no longer active"); address signer = hash.recover(signature); _checkValidSigner(signer); _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msgValue - totalPrice); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint(uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint(uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint(version, amount, pricesAndTimestamps); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { require(_totalMinted + buyAmount <= maxSupply, "Over token supply limit"); require(buyAmount <= amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; uint256 msgValue = msg.value; require(msgValue >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint(version, amount, pricesAndTimestamps); require(!_cancelledOrFinalizedSales[hash], "Signature no longer active"); address signer = hash.recover(signature); _checkValidSigner(signer); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, unitPrice, hash); payable(_msgSender()).transfer(msgValue - totalPrice); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash(_hashForAllowList(allowedAddress, nonce, version, price, amount)); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount)); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash(_hashForMint(version, amount, pricesAndTimestamps)); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner(), amount, pricesAndTimestamps, version)); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + randOffset); supplyLeft--; } } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require(maxMint == 0 || mintCount[buyer] + amount <= maxMint, "Buyer over mint maximum"); mintCount[buyer] += amount; uint256 nextTokenId = _totalMinted; if (isRevealed) { _mintRandomIndex(buyer, amount); } else { for (uint256 i = 0; i < amount; i++) { _safeMint(buyer, nextTokenId + i); } } _balances[buyer] += amount; _totalMinted += amount; } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); pragma solidity ^0.8.9; }
6,665,724
./full_match/1/0x541a2378589E280FDfDde6e53Fb5ECf98a853fC2/sources/src/BunniLpZapIn.sol
Wraps the user's ETH input into WETH Should be used as part of a multicall to convert the user's ETH input into WETH so that it can be swapped into other tokens.
function wrapEthInput() external payable { }
16,404,808
./full_match/1313161554/0xEF72330b252490648D01B242eCfFbb10b3C01B61/sources/contracts/JetStaking/JetStakingV2.sol
move all the streams rewards for a user to the pending tokens account is the staker address
function _moveAllRewardsToPending(address account) internal virtual { uint256 streamsLength = streams.length; for (uint256 i = 1; i < streamsLength; i++) { if (streams[i].status == StreamStatus.ACTIVE) _moveRewardsToPending(account, i); } }
13,233,226
/** *Submitted for verification at Etherscan.io on 2022-03-16 */ // SPDX-License-Identifier: MIT /** * @title T.O.T.A Contract by 7K Labs - Props to Chiru Labs for that erc721A goodness * * __________________________________________________________ * /\____/\\\\\\\\\\\\\\\___/\\\______/\\\_____/\\\___________\ * \/\___\/////////////\\\__\/\\\____/\\\/_____\/\\\___________\ * \/\______________/\\\/___\/\\\__/\\\/_______\/\\\___________\ * \/\____________/\\\/_____\/\\\/\\\/_________\/\\\___________\ * \/\__________/\\\/_______\/\\\\/\\\_________\/\\\___________\ * \/\________/\\\/_________\/\\\\///\\\_______\/\\\___________\ * \/\______/\\\/___________\/\\\__\///\\\_____\/\\\___________\ * \/\____/\\\/_____________\/\\\____\///\\\___\/\\\\\\\\\\\\\_\ * \/\___\///_______________\///_______\///____\/////////////__\ * \/\_________________________________________________________\ * \/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ * */ // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } pragma solidity >=0.7.0 <0.9.0; contract TribesOfTheAftermathTOTA is ERC721A, Ownable { using Strings for uint256; string internal contractName = "Tribes of the Aftermath TOTA"; string internal contractAbbr = "TOTA"; string public uriPrefix = ""; string public uriSuffix = ""; string public hiddenMetadataUri = "ipfs://QmQF6vN693xtnbtGNw4HVT6UdmQKuxvDxe59dG8w3NzaHv/tota.json"; bool public isRevealed = false; uint256 public preSaleCost = 0.08 ether; uint256 public pubSaleCost = 0.08 ether; uint256 public maxPreSalePerWallet = 5; uint256 public maxPubSalePerWallet = 20; uint256 public maxMintAmountPerTx = 10; uint256 public maxSupply = 8888; uint256 private ownerMintOnDeployment = 1; uint256 private ownerReserved = 150; bool public isSaleActive = false; bool public isPreSaleActive = true; // 0 = bypass, 1 = off-chain, 2 = on-chain uint256 public preSaleType = 1; address[] internal whitelistedAddresses; bytes32 public merkleRoot = 0xc6d7e6e2d994b666611235bdf1714dc30f20b966386a81ce610273f349dedb39; // team wallet addresses address internal raWallet = 0xe23D436Fc2F715d2B4Ec402511965E1474699fc9; address internal jrWallet = 0x6E035e0Dbd225E97AA171b87902ce6fe8527f16C; address internal tmWallet = 0xDac0B32df6DCFE658Af3bd1Fdf0c95D2af0b678A; address internal dgWallet = 0x6d587352dF7e0C377E87983586459609e9baf94e; address internal scWallet = 0xa130D1133Ef1A84F39B84467b16f5A0DD0577d4A; address internal spWallet = 0x56df8E01CC2fE2e1e01f6A0ee9B79c5aE54f3560; address internal devWallet = 0x1C81E289886544A04691936B13570e9B35495746; address internal teamWallet = 0x1C5b3F89D3Acf80223E2484897D2e38cF61E7c20; constructor() ERC721A(contractName, contractAbbr) { setHiddenMetadataUri(hiddenMetadataUri); _safeMint(teamWallet, ownerMintOnDeployment); } /** * @dev keeps track of the wallets that have minted during the whitelist and how many tokens they have minted */ struct Minter { bool exists; uint256 hasMintedByWhitelist; uint256 hasMintedInPublicSale; } mapping(address => Minter) public minters; /** * @dev public mint function takes in the amount of tokens to mint */ function mintPubSale(uint256 _mintAmount) public payable { require(isSaleActive, "Sale is not active!"); require(!isPreSaleActive, "Pre Sale is active!"); require(totalSupply() + _mintAmount <= maxSupply - ownerReserved, "Max supply exceeded!"); require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(msg.value >= pubSaleCost * _mintAmount, "Insufficient funds!"); require( minters[msg.sender].hasMintedInPublicSale + _mintAmount <= maxPubSalePerWallet, "Exceeds per wallet limit." ); if (!minters[msg.sender].exists) minters[msg.sender].exists = true; minters[msg.sender].hasMintedInPublicSale = minters[msg.sender].hasMintedInPublicSale + _mintAmount; _safeMint(msg.sender, _mintAmount); } /** * @dev presale mint function takes in the amount of tokens to mint and the proof for the merkel tree * if the merkle tree is not being used then feed in an empty array ([]) or if doing it from * etherscan feed in 0x0000000000000000000000000000000000000000000000000000000000000000 */ function mintPreSale(uint256 _mintAmount, bytes32[] calldata _markleProof) public payable { require(isSaleActive, "Sale is not active!"); require(totalSupply() + _mintAmount <= maxSupply - ownerReserved, "Max supply exceeded!"); require(isPreSaleActive, "Pre Sale is not active!"); require(msg.value >= preSaleCost * _mintAmount, "Insufficient funds!"); require(_mintAmount > 0, "Invalid mint amount!"); require(_mintAmount <= maxPreSalePerWallet, "Exceeds per wallet presale limit."); if (preSaleType == 1) require(isWhitelistedByMerkle(_markleProof, msg.sender), "You are not whitelisted."); if (preSaleType == 2) require(isWhitelistedByAddress(msg.sender), "You are not whitelisted."); require( minters[msg.sender].hasMintedByWhitelist + _mintAmount <= maxPreSalePerWallet, "Exceeds per wallet presale limit." ); if (!minters[msg.sender].exists) minters[msg.sender].exists = true; minters[msg.sender].hasMintedByWhitelist = minters[msg.sender].hasMintedByWhitelist + _mintAmount; _safeMint(msg.sender, _mintAmount); } /** * @dev returns an array of token IDs that the wallet owns */ function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 0; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } /** * @dev tests whether the wallet address has been whitelisted by the merkle tree by verifying * the proof provided to the function */ function isWhitelistedByMerkle(bytes32[] calldata _markleProof, address _user) public view returns(bool) { bytes32 leaf = keccak256(abi.encodePacked(_user)); return MerkleProof.verify(_markleProof, merkleRoot, leaf); } /** * @dev tests whether the wallet address has been whitelisted by the checking the whitelistedAddresses * array and returning a true/false flag */ function isWhitelistedByAddress(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } /** * @dev a simple `is whitelisted` function which tests the following things * 1) is the sale is active and the presale not active (public sale is active) - returns true * 2) presale type is 1 (merkle tree) - calls the isWhitelistedByMerkle() function * 3) presale type is 2 (standard whitelist) - calls the isWhitelistedByAddress() function * 4) if the above is not met, then return false */ function isWhitelisted(bytes32[] calldata _markleProof, address _user) public view returns(bool) { if (isSaleActive && !isPreSaleActive) { return true; } if (preSaleType == 0) { return true; } if (preSaleType == 1) { return isWhitelistedByMerkle(_markleProof, _user); } if (preSaleType == 2) { return isWhitelistedByAddress(_user); } return false; } /** * @dev returns all whitelisted addresses in an array */ function getWhitelistAddresses() public view returns(address[] memory) { return whitelistedAddresses; } /** * @dev returns the token URI - will return the hidden metadata if the isRevealed state is false */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId),"ERC721Metadata: URI query for nonexistent token"); if (isRevealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } /** * @dev returns the base token sufix */ function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } /** * @dev returns the remaining public supply */ function getRemainingPublicSupply() public view returns (uint256) { return maxSupply - ownerReserved - totalSupply(); } /** * @dev returns the remaining reserved supply */ function getRemainingReservedSupply() public view returns (uint256) { return ownerReserved; } // // only owner functions /** * @dev sets the presale type - 1 is merkle tree validation and 2 is standard whitelist array */ function setPreSaleType(uint8 _type) public onlyOwner { // 0 = bypass whitelist, 1 = merkle tree, 2 = wl addresses require(_type == 0 || _type == 1 || _type == 2, "Invalid whitelist type."); preSaleType = _type; } /** * @dev sets the merkle root for the verification (wl type 1) */ function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } /** * @dev sets the array for the whitelists (wl type 2) * this will reset the original whitelist with whatever is set here. therefore the entire * whitelist needs to be provided again */ function setWhitelistAddresses(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } /** * @dev allows the contract owner to manually mint a set amount to a specified wallet address * where only the gas needs to be paid. these tokens come out of the public supply */ function sendPublicTokenToAddr(uint256 _mintAmount, address _receiver) public onlyOwner { require(totalSupply() + _mintAmount <= maxSupply - ownerReserved, "Max supply exceeded!"); require(_mintAmount > 0, "Invalid mint amount"); _safeMint(_receiver, _mintAmount); } /** * @dev allows the contract owner to manually mint a set amount to a specified wallet address * where only the gas needs to be paid. these tokens come out of the reserved/non-public supply */ function sendReservedTokenToAddr(uint256 _mintAmount, address _receiver) public onlyOwner { require(ownerReserved > 0 && _mintAmount <= ownerReserved, "Exceeds reserved supply!"); require(_mintAmount > 0, "Invalid mint amount"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); setReservedSupply(ownerReserved - _mintAmount); _safeMint(_receiver, _mintAmount); } /** * @dev allows the contract owner to change the amount they have reserved */ function setReservedSupply(uint256 _amount) public onlyOwner { require(_amount >= 0 && _amount <= maxSupply - totalSupply(), "Exceeds remaining supply!"); ownerReserved = _amount; } /** * @dev flips the revealed state from false to true. it can be flipped back but all metadata on OpenSea * would need to be refresed again. */ function flipRevealedState() public onlyOwner { isRevealed = !isRevealed; } /** * @dev sets the presale price of the token. this has to be sent through in wei and not eth * eg 1 eth = 1000000000000000000 wei */ function setPreSaleCost(uint256 _cost) public onlyOwner { preSaleCost = _cost; } /** * @dev sets the public sale price of the token. this has to be sent through in wei and not eth * eg 1 eth = 1000000000000000000 wei */ function setPubSaleCost(uint256 _cost) public onlyOwner { pubSaleCost = _cost; } /** * @dev sets the max amount per transaction in the public sale */ function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } /** * @dev sets the max amount per wallet in the presale */ function setMaxPreSalePerWallet(uint256 _maxMintAmount) public onlyOwner { require(_maxMintAmount > 0, "Must be greater than zero"); maxPreSalePerWallet = _maxMintAmount; } /** * @dev sets the max amount per wallet in the public sale */ function setMaxPubSalePerWallet(uint256 _maxMintAmount) public onlyOwner { require(_maxMintAmount > 0, "Must be greater than zero"); maxPubSalePerWallet = _maxMintAmount; } /** * @dev sets the not revealed metadata path (if using ipfs if must be entered ipfs://<CID>/hidden.json) */ function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } /** * @dev sets the path to the token (if using ipfs if must be entered ipfs://<CID>/) with the trailing slash * an api can just be called as eg https://api.myurl.com/token/ */ function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } /** * @dev sets the uri suffix (ie if the metadata is stored on ipfs this should be set to .json) */ function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } /** * @dev sets the uri suffix to blank if it has been set and you want to use an api to call your metadata */ function setUriSuffixToBlank() public onlyOwner { uriSuffix = ""; } /** * @dev sets the sale state (either true to false or false to true) this must be set to true for any * public minting to occur (even the presale) */ function flipSaleState() public onlyOwner { isSaleActive = !isSaleActive; } /** * @dev sets the presale state (either true to false or false to true) this must be set to true for any * presale functionality to occur) */ function flipPreSaleState() public onlyOwner { isPreSaleActive = !isPreSaleActive; } /** * @dev called to withdraw funds from the contract. this will pay x% to a developer wallet and the remaining balance * to the contract owner. the dev wallet and % are set at the top of this contract */ function withdraw() public onlyOwner { uint256 _balance = address(this).balance; (bool ra, ) = payable(raWallet).call{value: _balance * 14 / 100}(""); require(ra); (bool jr, ) = payable(jrWallet).call{value: _balance * 28 / 100}(""); require(jr); (bool tm, ) = payable(tmWallet).call{value: _balance * 3 / 100}(""); require(tm); (bool dg, ) = payable(dgWallet).call{value: _balance * 4 / 100}(""); require(dg); (bool sc, ) = payable(scWallet).call{value: _balance * 15 / 100}(""); require(sc); (bool sp, ) = payable(spWallet).call{value: _balance * 8 / 100}(""); require(sp); (bool dw, ) = payable(devWallet).call{value: _balance * 10 / 100}(""); require(dw); (bool tw, ) = payable(teamWallet).call{value: address(this).balance}(""); require(tw); } }
sets the max amount per wallet in the public sale/
function setMaxPubSalePerWallet(uint256 _maxMintAmount) public onlyOwner { require(_maxMintAmount > 0, "Must be greater than zero"); maxPubSalePerWallet = _maxMintAmount; }
10,965,978
./full_match/137/0x462ab8E39886a2F94D8DDa274a0f4BDdee6CE634/sources/contracts/Administerable.sol
Remove oneself from the admin role.
function renounceGameControl() public virtual { renounceRole(_GAME_CONTROL_ROLE, msg.sender); }
4,725,811
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./spool/SpoolExternal.sol"; /** * @notice Implementation of the central Spool contract. * * @dev * The Spool implementation is the central part of the system. * All the assets flow through this contract and are deposited * to the integrated protocols. * * Spool implementation consists of following contracts: * 1. BaseStorage: stores common variables with all the strategy adapters (they are execuret as delegatecode) * 2. SpoolBase: holds Spool state variables and provides some of the common vault functions * 3. SpoolStrategy: implements the logic of how to interact with the strategies * 4. SpoolDoHardWork: implements functions to process the do hard work * 5. SpoolReallocation: adjusts vault reallocation that takes place at the next do hard work * 6. SpoolExternal: exposes functons to interact with the Spool from the vault (deposit/withdraw/redeem) * 7. Spool: implements a constructor to deploy a contracts */ contract Spool is SpoolExternal { /** * @notice Initializes the central Spool contract values * * @param _spoolOwner the spool owner contract * @param _controller responsible for providing the source of truth * @param _fastWithdraw allows fast withdraw of user shares */ constructor( ISpoolOwner _spoolOwner, IController _controller, address _fastWithdraw ) SpoolBase( _spoolOwner, _controller, _fastWithdraw ) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // 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 pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; import "./ISwapData.sol"; interface IBaseStrategy { function underlying() external view returns (IERC20); function getStrategyBalance() external view returns (uint128); function getStrategyUnderlyingWithRewards() external view returns(uint128); function process(uint256[] calldata, bool, SwapData[] calldata) external; function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128); function processDeposit(uint256[] calldata) external; function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128); function claimRewards(SwapData[] calldata) external; function emergencyWithdraw(address recipient, uint256[] calldata data) external; function initialize() external; function disable() external; } struct ProcessReallocationData { uint128 sharesToWithdraw; uint128 optimizedShares; uint128 optimizedWithdrawnAmount; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IController { /* ========== FUNCTIONS ========== */ function strategies(uint256 i) external view returns (address); function validStrategy(address strategy) external view returns (bool); function validVault(address vault) external view returns (bool); function getStrategiesCount() external view returns(uint8); function supportedUnderlying(IERC20 underlying) external view returns (bool); function getAllStrategies() external view returns (address[] memory); function verifyStrategies(address[] calldata _strategies) external view; function transferToSpool( address transferFrom, uint256 amount ) external; function checkPaused() external view; /* ========== EVENTS ========== */ event EmergencyWithdrawStrategy(address indexed strategy); event EmergencyRecipientUpdated(address indexed recipient); event EmergencyWithdrawerUpdated(address indexed withdrawer, bool set); event PauserUpdated(address indexed user, bool set); event UnpauserUpdated(address indexed user, bool set); event VaultCreated(address indexed vault, address underlying, address[] strategies, uint256[] proportions, uint16 vaultFee, address riskProvider, int8 riskTolerance); event StrategyAdded(address strategy); event StrategyRemoved(address strategy); event VaultInvalid(address vault); event DisableStrategy(address strategy); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./vault/IVaultRestricted.sol"; import "./vault/IVaultIndexActions.sol"; import "./vault/IRewardDrip.sol"; import "./vault/IVaultBase.sol"; import "./vault/IVaultImmutable.sol"; interface IVault is IVaultRestricted, IVaultIndexActions, IRewardDrip, IVaultBase, IVaultImmutable {} // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolBase { /* ========== FUNCTIONS ========== */ function getCompletedGlobalIndex() external view returns(uint24); function getActiveGlobalIndex() external view returns(uint24); function isMidReallocation() external view returns (bool); /* ========== EVENTS ========== */ event ReallocationTableUpdated( uint24 indexed index, bytes32 reallocationTableHash ); event ReallocationTableUpdatedWithTable( uint24 indexed index, bytes32 reallocationTableHash, uint256[][] reallocationTable ); event DoHardWorkCompleted(uint24 indexed index); event SetAllocationProvider(address actor, bool isAllocationProvider); event SetIsDoHardWorker(address actor, bool isDoHardWorker); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolDoHardWork { /* ========== EVENTS ========== */ event DoHardWorkStrategyCompleted(address indexed strat, uint256 indexed index); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../ISwapData.sol"; interface ISpoolExternal { /* ========== FUNCTIONS ========== */ function deposit(address strategy, uint128 amount, uint256 index) external; function withdraw(address strategy, uint256 vaultProportion, uint256 index) external; function fastWithdrawStrat(address strat, address underlying, uint256 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external returns(uint128); function redeem(address strat, uint256 index) external returns (uint128, uint128); function redeemUnderlying(uint128 amount) external; function redeemReallocation(address[] calldata vaultStrategies, uint256 depositProportions, uint256 index) external; function removeShares(address[] calldata vaultStrategies, uint256 vaultProportion) external returns(uint128[] memory); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolReallocation { event StartReallocation(uint24 indexed index); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolStrategy { /* ========== FUNCTIONS ========== */ function getUnderlying(address strat) external returns (uint128); function getVaultTotalUnderlyingAtIndex(address strat, uint256 index) external view returns(uint128); function addStrategy(address strat) external; function disableStrategy(address strategy, bool skipDisable) external; function runDisableStrategy(address strategy) external; function emergencyWithdraw( address strat, address withdrawRecipient, uint256[] calldata data ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IRewardDrip { /* ========== STRUCTS ========== */ // The reward configuration struct, containing all the necessary data of a typical Synthetix StakingReward contract struct RewardConfiguration { uint32 rewardsDuration; uint32 periodFinish; uint192 rewardRate; // rewards per second multiplied by accuracy uint32 lastUpdateTime; uint224 rewardPerTokenStored; mapping(address => uint256) userRewardPerTokenPaid; mapping(address => uint256) rewards; } /* ========== FUNCTIONS ========== */ function getActiveRewards(address account) external; function tokenBlacklist(IERC20 token) view external returns(bool); /* ========== EVENTS ========== */ event RewardPaid(IERC20 token, address indexed user, uint256 reward); event RewardAdded(IERC20 indexed token, uint256 amount, uint256 duration); event RewardExtended(IERC20 indexed token, uint256 amount, uint256 leftover, uint256 duration, uint32 periodFinish); event RewardRemoved(IERC20 indexed token); event PeriodFinishUpdated(IERC20 indexed token, uint32 periodFinish); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./IVaultDetails.sol"; interface IVaultBase { /* ========== FUNCTIONS ========== */ function initialize(VaultInitializable calldata vaultInitializable) external; /* ========== STRUCTS ========== */ struct User { uint128 instantDeposit; // used for calculating rewards uint128 activeDeposit; // users deposit after deposit process and claim uint128 owed; // users owed underlying amount after withdraw has been processed and claimed uint128 withdrawnDeposits; // users withdrawn deposit, used to calculate performance fees uint128 shares; // users shares after deposit process and claim } /* ========== EVENTS ========== */ event Claimed(address indexed member, uint256 claimAmount); event Deposit(address indexed member, uint256 indexed index, uint256 amount); event Withdraw(address indexed member, uint256 indexed index, uint256 shares); event WithdrawFast(address indexed member, uint256 shares); event StrategyRemoved(uint256 i, address strategy); event TransferVaultOwner(address owner); event LowerVaultFee(uint16 fee); event UpdateName(string name); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; struct VaultDetails { address underlying; address[] strategies; uint256[] proportions; address creator; uint16 vaultFee; address riskProvider; int8 riskTolerance; string name; } struct VaultInitializable { string name; address owner; uint16 fee; address[] strategies; uint256[] proportions; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../../external/@openzeppelin/token/ERC20/IERC20.sol"; struct VaultImmutables { IERC20 underlying; address riskProvider; int8 riskTolerance; } interface IVaultImmutable { /* ========== FUNCTIONS ========== */ function underlying() external view returns (IERC20); function riskProvider() external view returns (address); function riskTolerance() external view returns (int8); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface IVaultIndexActions { /* ========== STRUCTS ========== */ struct IndexAction { uint128 depositAmount; uint128 withdrawShares; } struct LastIndexInteracted { uint128 index1; uint128 index2; } struct Redeem { uint128 depositShares; uint128 withdrawnAmount; } /* ========== EVENTS ========== */ event VaultRedeem(uint indexed globalIndex); event UserRedeem(address indexed member, uint indexed globalIndex); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface IVaultRestricted { /* ========== FUNCTIONS ========== */ function reallocate( address[] calldata vaultStrategies, uint256 newVaultProportions, uint256 finishedIndex, uint24 activeIndex ) external returns (uint256[] memory, uint256); function payFees(uint256 profit) external returns (uint256 feesPaid); /* ========== EVENTS ========== */ event Reallocate(uint24 indexed index, uint256 newProportions); } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; library Bitwise { function get8BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) { return (bitwiseData >> (8 * i)) & type(uint8).max; } // 14 bits is used for strategy proportions in a vault as FULL_PERCENT is 10_000 function get14BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) { return (bitwiseData >> (14 * i)) & (16_383); // 16.383 is 2^14 - 1 } function set14BitUintByIndex(uint256 bitwiseData, uint256 i, uint256 num14bit) internal pure returns(uint256) { return bitwiseData + (num14bit << (14 * i)); } function reset14BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) { return bitwiseData & (~(16_383 << (14 * i))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** * @notice Library to provide utils for hashing and hash compatison of Spool related data */ library Hash { function hashReallocationTable(uint256[][] memory reallocationTable) internal pure returns(bytes32) { return keccak256(abi.encode(reallocationTable)); } function hashStrategies(address[] memory strategies) internal pure returns(bytes32) { return keccak256(abi.encodePacked(strategies)); } function sameStrategies(address[] memory strategies1, address[] memory strategies2) internal pure returns(bool) { return hashStrategies(strategies1) == hashStrategies(strategies2); } function sameStrategies(address[] memory strategies, bytes32 strategiesHash) internal pure returns(bool) { return hashStrategies(strategies) == strategiesHash; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../external/@openzeppelin/utils/SafeCast.sol"; /** * @notice A collection of custom math ustils used throughout the system */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { return SafeCast.toUint128(((mul1 * mul2) / div)); } function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { unchecked { return uint128((mul1 * mul2) / div); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** @notice Handle setting zero value in a storage word as uint128 max value. * * @dev * The purpose of this is to avoid resetting a storage word to the zero value; * the gas cost of re-initializing the value is the same as setting the word originally. * so instead, if word is to be set to zero, we set it to uint128 max. * * - anytime a word is loaded from storage: call "get" * - anytime a word is written to storage: call "set" * - common operations on uints are also bundled here. * * NOTE: This library should ONLY be used when reading or writing *directly* from storage. */ library Max128Bit { uint128 internal constant ZERO = type(uint128).max; function get(uint128 a) internal pure returns(uint128) { return (a == ZERO) ? 0 : a; } function set(uint128 a) internal pure returns(uint128){ return (a == 0) ? ZERO : a; } function add(uint128 a, uint128 b) internal pure returns(uint128 c){ a = get(a); c = set(a + b); } } // SPDX-License-Identifier: BUSL-1.1 import "../interfaces/ISwapData.sol"; pragma solidity 0.8.11; /// @notice Strategy struct for all strategies struct Strategy { uint128 totalShares; /// @notice Denotes strategy completed index uint24 index; /// @notice Denotes whether strategy is removed /// @dev after removing this value can never change, hence strategy cannot be added back again bool isRemoved; /// @notice Pending geposit amount and pending shares withdrawn by all users for next index Pending pendingUser; /// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index Pending pendingUserNext; /// @dev Usually a temp variable when compounding mapping(address => uint256) pendingRewards; /// @dev Usually a temp variable when compounding uint128 pendingDepositReward; /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it uint256 lpTokens; // ----- REALLOCATION VARIABLES ----- bool isInDepositPhase; /// @notice Used to store amount of optimized shares, so they can be substracted at the end /// @dev Only for temporary use, should be reset to 0 in same transaction uint128 optimizedSharesWithdrawn; /// @dev Underlying amount pending to be deposited from other strategies at reallocation /// @dev resets after the strategy reallocation DHW is finished uint128 pendingReallocateDeposit; /// @notice Stores amount of optimized underlying amount when reallocating /// @dev resets after the strategy reallocation DHW is finished /// @dev This is "virtual" amount that was matched between this strategy and others when reallocating uint128 pendingReallocateOptimizedDeposit; // ------------------------------------ /// @notice Total underlying amoung at index mapping(uint256 => TotalUnderlying) totalUnderlying; /// @notice Batches stored after each DHW with index as a key /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users mapping(uint256 => Batch) batches; /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate) /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation mapping(uint256 => BatchReallocation) reallocationBatches; /// @notice Vaults holding this strategy shares mapping(address => Vault) vaults; /// @notice Future proof storage mapping(bytes32 => AdditionalStorage) additionalStorage; /// @dev Make sure to reset it to 0 after emergency withdrawal uint256 emergencyPending; } /// @notice Unprocessed deposit underlying amount and strategy share amount from users struct Pending { uint128 deposit; uint128 sharesToWithdraw; } /// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index struct TotalUnderlying { uint128 amount; uint128 totalShares; } /// @notice Stored after executing DHW for each index. /// @dev This is used for vaults to redeem their deposit. struct Batch { /// @notice total underlying deposited in index uint128 deposited; uint128 depositedReceived; uint128 depositedSharesReceived; uint128 withdrawnShares; uint128 withdrawnReceived; } /// @notice Stored after executing reallocation DHW each index. struct BatchReallocation { /// @notice Deposited amount received from reallocation uint128 depositedReallocation; /// @notice Received shares from reallocation uint128 depositedReallocationSharesReceived; /// @notice Used to know how much tokens was received for reallocating uint128 withdrawnReallocationReceived; /// @notice Amount of shares to withdraw for reallocation uint128 withdrawnReallocationShares; } /// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working) struct Vault { uint128 shares; /// @notice Withdrawn amount as part of the reallocation uint128 withdrawnReallocationShares; /// @notice Index to action mapping(uint256 => VaultBatch) vaultBatches; } /// @notice Stores deposited and withdrawn shares by the vault struct VaultBatch { /// @notice Vault index to deposited amount mapping uint128 deposited; /// @notice Vault index to withdrawn user shares mapping uint128 withdrawnShares; } /// @notice Used for reallocation calldata struct VaultData { address vault; uint8 strategiesCount; uint256 strategiesBitwise; uint256 newProportions; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the withdraw part of the reallocation DHW struct ReallocationWithdrawData { uint256[][] reallocationTable; StratUnderlyingSlippage[] priceSlippages; RewardSlippages[] rewardSlippages; uint256[] stratIndexes; uint256[][] slippages; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the deposit part of the reallocation DHW struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; } /// @notice In case some adapters need extra storage struct AdditionalStorage { uint256 value; address addressValue; uint96 value96; } /// @notice Strategy total underlying slippage, to verify validity of the strategy state struct StratUnderlyingSlippage { uint128 min; uint128 max; } /// @notice Containig information if and how to swap strategy rewards at the DHW /// @dev Passed in by the do-hard-worker struct RewardSlippages { bool doClaim; SwapData[] swapData; } /// @notice Helper struct to compare strategy share between eachother /// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating) struct PriceData { uint128 totalValue; uint128 totalShares; } /// @notice Strategy reallocation values after reallocation optimization of shares was calculated struct ReallocationShares { uint128[] optimizedWithdraws; uint128[] optimizedShares; uint128[] totalSharesWithdrawn; } /// @notice Shared storage for multiple strategies /// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool) struct StrategiesShared { uint184 value; uint32 lastClaimBlock; uint32 lastUpdateBlock; uint8 stratsCount; mapping(uint256 => address) stratAddresses; mapping(bytes32 => uint256) bytesValues; } /// @notice Base storage shared betweek Spool contract and Strategies /// @dev this way we can use same values when performing delegate call /// to strategy implementations from the Spool contract abstract contract BaseStorage { // ----- DHW VARIABLES ----- /// @notice Force while DHW (all strategies) to be executed in only one transaction /// @dev This is enforced to increase the gas efficiency of the system /// Can be removed by the DAO if gas gost of the strategies goes over the block limit bool internal forceOneTxDoHardWork; /// @notice Global index of the system /// @dev Insures the correct strategy DHW execution. /// Every strategy in the system must be equal or one less than global index value /// Global index increments by 1 on every do-hard-work uint24 public globalIndex; /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed uint8 internal doHardWorksLeft; // ----- REALLOCATION VARIABLES ----- /// @notice Used for offchain execution to get the new reallocation table. bool internal logReallocationTable; /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index /// @dev only used when reallocating /// after it reaches 0, deposit phase of the reallocation can begin uint8 public withdrawalDoHardWorksLeft; /// @notice Index at which next reallocation is set uint24 public reallocationIndex; /// @notice 2D table hash containing information of how strategies should be reallocated between eachother /// @dev Created when allocation provider sets reallocation for the vaults /// This table is stored as a hash in the system and verified on reallocation DHW /// Resets to 0 after reallocation DHW is completed bytes32 internal reallocationTableHash; /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating. /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton /// Resets when DHW is completed bytes32 internal reallocationStrategiesHash; // ----------------------------------- /// @notice Denoting if an address is the do-hard-worker mapping(address => bool) public isDoHardWorker; /// @notice Denoting if an address is the allocation provider mapping(address => bool) public isAllocationProvider; /// @notice Strategies shared storage /// @dev used as a helper storage to save common inoramation mapping(bytes32 => StrategiesShared) internal strategiesShared; /// @notice Mapping of strategy implementation address to strategy system values mapping(address => Strategy) public strategies; /// @notice Flag showing if disable was skipped when a strategy has been removed /// @dev If true disable can still be run mapping(address => bool) internal _skippedDisable; /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed /// @dev If true emergency withdraw can still be executed mapping(address => bool) internal _awaitingEmergencyWithdraw; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; /// @title Common Spool contracts constants abstract contract BaseConstants { /// @dev 2 digits precision uint256 internal constant FULL_PERCENT = 100_00; /// @dev Accuracy when doing shares arithmetics uint256 internal constant ACCURACY = 10**30; } /// @title Contains USDC token related values abstract contract USDC { /// @notice USDC token contract address IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../interfaces/ISpoolOwner.sol"; /// @title Logic to help check whether the caller is the Spool owner abstract contract SpoolOwnable { /// @notice Contract that checks if address is Spool owner ISpoolOwner internal immutable spoolOwner; /** * @notice Sets correct initial values * @param _spoolOwner Spool owner contract address */ constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } /** * @notice Checks if caller is Spool owner * @return True if caller is Spool owner, false otherwise */ function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } /// @notice Checks and throws if caller is not Spool owner function _onlyOwner() private view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } /// @notice Checks and throws if caller is not Spool owner modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../interfaces/IController.sol"; /// @title Facilitates checking if the system is paused or not abstract contract SpoolPausable { /* ========== STATE VARIABLES ========== */ /// @notice The controller contract that is consulted for a strategy's and vault's validity IController public immutable controller; /** * @notice Sets initial values * @param _controller Controller contract address */ constructor(IController _controller) { require( address(_controller) != address(0), "SpoolPausable::constructor: Controller contract address cannot be 0" ); controller = _controller; } /* ========== MODIFIERS ========== */ /// @notice Throws if system is paused modifier systemNotPaused() { controller.checkPaused(); _; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolBase.sol"; import "../shared/BaseStorage.sol"; import "../shared/SpoolOwnable.sol"; import "../shared/Constants.sol"; // libraries import "../libraries/Hash.sol"; // other imports import "../interfaces/IController.sol"; import "../shared/SpoolPausable.sol"; /** * @notice Implementation of the {ISpoolBase} interface. * * @dev * This implementation acts as the central code execution point of the Spool * system and is responsible for maintaining the balance sheet of each vault * based on the asynchronous deposit and withdraw system, redeeming vault * shares and withdrawals and performing doHardWork. */ abstract contract SpoolBase is ISpoolBase, BaseStorage, SpoolOwnable, SpoolPausable, BaseConstants { /* ========== STATE VARIABLES ========== */ /// @notice The fast withdraw contract that is used to quickly remove shares address internal immutable fastWithdraw; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the contract initial values * * @dev * Additionally, initializes the SPL reward data for * do hard work invocations. * * It performs certain pre-conditional validations to ensure the contract * has been initialized properly, such as valid addresses and reward configuration. * * @param _spoolOwner the spool owner contract address * @param _controller the controller contract address * @param _fastWithdraw the fast withdraw contract address */ constructor( ISpoolOwner _spoolOwner, IController _controller, address _fastWithdraw ) SpoolOwnable(_spoolOwner) SpoolPausable(_controller) { require( _fastWithdraw != address(0), "BaseSpool::constructor: FastWithdraw address cannot be 0" ); fastWithdraw = _fastWithdraw; globalIndex = 1; } /* ========== VIEWS ========== */ /** * @notice Checks whether Spool is mid reallocation * @return _isMidReallocation True if Spool is mid reallocation */ function isMidReallocation() public view override returns (bool _isMidReallocation) { if (reallocationIndex == globalIndex && !_isBatchComplete()) { _isMidReallocation = true; } } /** * @notice Returns strategy shares belonging to a vauld * @param strat Strategy address * @param vault Vault address * @return Shares for a specific vault - strategy combination */ function getStratVaultShares(address strat, address vault) external view returns(uint128) { return strategies[strat].vaults[vault].shares; } /** * @notice Returns completed index (all strategies in the do hard work have been processed) * @return Completed index */ function getCompletedGlobalIndex() public override view returns(uint24) { if (_isBatchComplete()) { return globalIndex; } return globalIndex - 1; } /** * @notice Returns next possible index to interact with * @return Next active global index */ function getActiveGlobalIndex() public override view returns(uint24) { return globalIndex + 1; } /** * @notice Check if batch complete * @return isComplete True if all strategies have the same index */ function _isBatchComplete() internal view returns(bool isComplete) { if (doHardWorksLeft == 0) { isComplete = true; } } /** * @notice Decode revert message * @param _returnData Data returned by delegatecall * @return Revert string */ function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // if the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "SILENT"; assembly { // slice the sig hash _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // all that remains is the revert string } /* ========== DELEGATECALL HELPERS ========== */ /** * @notice this function allows static-calling an arbitrary write function from Spool, off-chain, and returning the result. The general purpose is for the calculation of * rewards in an implementation contract, where the reward calculation contains state changes that can't be easily gathered without calling from the Spool contract. * The require statement ensure that this comes from a static call off-chain, which can substitute an arbitrary address. * The 'one' address is used. The zero address could be used, but due to the prevalence of zero address checks, the internal calls would likely fail. * It has the same level of security as finding any arbitrary address, including address zero. * * @param implementation Address which to relay the call to * @param payload Payload to relay to the implementation * @return Response returned by the relayed call */ function relay(address implementation, bytes memory payload) external returns(bytes memory) { require(msg.sender == address(1)); return _relay(implementation, payload); } /** * @notice Relays the particular action to the strategy via delegatecall. * @param strategy Strategy address to delegate the call to * @param payload Data to pass when delegating call * @return Response received when delegating call */ function _relay(address strategy, bytes memory payload) internal returns (bytes memory) { (bool success, bytes memory data) = strategy.delegatecall(payload); if (!success) revert(_getRevertMsg(data)); return data; } /* ========== CONFIGURATION ========== */ /** * @notice Set allocation provider role for given user * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @param user Address to set the role for * @param _isAllocationProvider Whether the user is assigned the role or not */ function setAllocationProvider(address user, bool _isAllocationProvider) external onlyOwner { isAllocationProvider[user] = _isAllocationProvider; emit SetAllocationProvider(user, _isAllocationProvider); } /** * @notice Set doHardWorker role for given user * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @param user Address to set the role for * @param _isDoHardWorker Whether the user is assigned the role or not */ function setDoHardWorker(address user, bool _isDoHardWorker) external onlyOwner { isDoHardWorker[user] = _isDoHardWorker; emit SetIsDoHardWorker(user, _isDoHardWorker); } /** * @notice Set the flag to force "do hard work" to be executed in one transaction. * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @param doForce Enable/disable running in one transactions */ function setForceOneTxDoHardWork(bool doForce) external onlyOwner { forceOneTxDoHardWork = doForce; } /** * @notice Set the flag to log reallocation proportions on change. * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @dev Used for offchain execution to get the new reallocation table. * @param doLog Whether to log or not */ function setLogReallocationTable(bool doLog) external onlyOwner { logReallocationTable = doLog; } /** * @notice Set awaiting emergency withdraw flag for the strategy. * * @dev * Only for emergency case where withdrawing the first time doesn't fully work. * * Requirements: * * - the caller must be the Spool owner (Spool DAO) * * @param strat strategy to set * @param isAwaiting Flag value */ function setAwaitingEmergencyWithdraw(address strat, bool isAwaiting) external onlyOwner { _awaitingEmergencyWithdraw[strat] = isAwaiting; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Ensures that given address is a valid vault */ function _isVault(address vault) internal view { require( controller.validVault(vault), "NTVLT" ); } /** * @notice Ensures that strategy wasn't removed */ function _notRemoved(address strat) internal view { require( !strategies[strat].isRemoved, "OKSTRT" ); } /** * @notice If batch is complete it resets reallocation variables and emits an event * @param isReallocation If true, reset the reallocation variables */ function _finishDhw(bool isReallocation) internal { if (_isBatchComplete()) { // reset reallocation variables if (isReallocation) { reallocationIndex = 0; reallocationTableHash = 0; } emit DoHardWorkCompleted(globalIndex); } } /* ========== PRIVATE FUNCTIONS ========== */ /** * @notice Ensures that the caller is the controller */ function _onlyController() private view { require( msg.sender == address(controller), "OCTRL" ); } /** * @notice Ensures that the caller is the fast withdraw */ function _onlyFastWithdraw() private view { require( msg.sender == fastWithdraw, "OFWD" ); } /** * @notice Ensures that there is no pending reallocation */ function _noPendingReallocation() private view { require( reallocationTableHash == 0, "NORLC" ); } /** * @notice Ensures that strategy is removed */ function _onlyRemoved(address strat) private view { require( strategies[strat].isRemoved, "RMSTR" ); } /** * @notice Verifies given strategies * @param strategies Array of strategies to verify */ function _verifyStrategies(address[] memory strategies) internal view { controller.verifyStrategies(strategies); } /** * @notice Ensures that the caller is allowed to execute do hard work */ function _onlyDoHardWorker() private view { require( isDoHardWorker[msg.sender], "ODHW" ); } /** * @notice Verifies the reallocation table against the stored hash * @param reallocationTable The data to verify */ function _verifyReallocationTable(uint256[][] memory reallocationTable) internal view { require(reallocationTableHash == Hash.hashReallocationTable(reallocationTable), "BRLC"); } /** * @notice Verifies the reallocation strategies against the stored hash * @param strategies Array of strategies to verify */ function _verifyReallocationStrategies(address[] memory strategies) internal view { require(Hash.sameStrategies(strategies, reallocationStrategiesHash), "BRLCSTR"); } /* ========== MODIFIERS ========== */ /** * @notice Throws if called by anyone else other than the controller */ modifier onlyDoHardWorker() { _onlyDoHardWorker(); _; } /** * @notice Throws if called by a non-valid vault */ modifier onlyVault() { _isVault(msg.sender); _; } /** * @notice Throws if called by anyone else other than the controller */ modifier onlyController() { _onlyController(); _; } /** * @notice Throws if the caller is not fast withdraw */ modifier onlyFastWithdraw() { _onlyFastWithdraw(); _; } /** * @notice Throws if given array of strategies is not valid */ modifier verifyStrategies(address[] memory strategies) { _verifyStrategies(strategies); _; } /** * @notice Throws if given array of reallocation strategies is not valid */ modifier verifyReallocationStrategies(address[] memory strategies) { _verifyReallocationStrategies(strategies); _; } /** * @notice Throws if caller does not have the allocation provider role */ modifier onlyAllocationProvider() { require( isAllocationProvider[msg.sender], "OALC" ); _; } /** * @notice Ensures that there is no pending reallocation */ modifier noPendingReallocation() { _noPendingReallocation(); _; } /** * @notice Throws strategy is removed */ modifier notRemoved(address strat) { _notRemoved(strat); _; } /** * @notice Throws strategy isn't removed */ modifier onlyRemoved(address strat) { _onlyRemoved(strat); _; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolDoHardWork.sol"; import "./SpoolStrategy.sol"; /** * @notice Spool part of implementation dealing with the do hard work * * @dev * Do hard work is the process of interacting with other protocols. * This process aggregates many actions together to act in as optimized * manner as possible. It optimizes for underlying assets and gas cost. * * Do hard work (DHW) is executed periodically. As users are depositing * and withdrawing, these actions are stored in the buffer system. * When executed the deposits and withdrawals are matched against * eachother to minimize slippage and protocol fees. This means that * for a normal DHW only deposit or withdrawal is executed and never * both in the same index. Both can only be if the DHW is processing * the reallocation as well. * * Each strategy DHW is executed once per index and then incremented. * When all strategies are incremented to the same index, the batch * is considered complete. As soon as a new batch starts (first strategy * in the new batch is processed) global index is incremented. * * Global index is always one more or equal to the strategy index. * This constraints the system so that all strategy DHWs have to be * executed to complete the batch. * * Do hard work can only be executed by the whitelisted addresses. * The whitelisting can be done only by the Spool DAO. * * Do hard work actions: * - deposit * - withdrawal * - compound rewards * - reallocate assets across protocols * */ abstract contract SpoolDoHardWork is ISpoolDoHardWork, SpoolStrategy { /* ========== DO HARD WORK ========== */ /** * @notice Executes do hard work of specified strategies. * * @dev * Requirements: * * - caller must be a valid do hard worker * - provided strategies must be valid * - reallocation is not pending for current index * - if `forceOneTxDoHardWork` flag is true all strategies should be executed in one transaction * - at least one strategy must be processed * - the system should not be paused * * @param stratIndexes Array of strategy indexes * @param slippages Array of slippage values to be used when depositing into protocols (e.g. minOut) * @param rewardSlippages Array of values containing information of if and how to swap reward tokens to strategy underlying * @param allStrategies Array of all valid strategy addresses in the system */ function batchDoHardWork( uint256[] memory stratIndexes, uint256[][] memory slippages, RewardSlippages[] memory rewardSlippages, address[] memory allStrategies ) external systemNotPaused onlyDoHardWorker verifyStrategies(allStrategies) { // update global index if this are first strategies in index if (_isBatchComplete()) { globalIndex++; doHardWorksLeft = uint8(allStrategies.length); } // verify reallocation is not set for the current index if (reallocationIndex == globalIndex) { // if reallocation is set, verify it was disabled require(reallocationTableHash == 0, "RLC"); // if yes, reset reallocation index reallocationIndex = 0; } require( stratIndexes.length > 0 && stratIndexes.length == slippages.length && stratIndexes.length == rewardSlippages.length, "BIPT" ); // check if DHW is forcen to be executen on one transaction if (forceOneTxDoHardWork) { require(stratIndexes.length == allStrategies.length, "1TX"); } // go over withdrawals and deposits for (uint256 i = 0; i < stratIndexes.length; i++) { address stratAddress = allStrategies[stratIndexes[i]]; _doHardWork(stratAddress, slippages[i], rewardSlippages[i]); _updatePending(stratAddress); _finishStrategyDoHardWork(stratAddress); } _updateDoHardWorksLeft(stratIndexes.length); // if DHW for index finished _finishDhw(false); } /** * @notice Process strategy DHW, deposit wnd withdraw * @dev Only executed when there is no reallocation for the DHW * @param strat Strategy address * @param slippages Array of slippage values to be used when depositing into protocols (e.g. minOut) * @param rewardSlippages Array of values containing information of if and how to swap reward tokens to strategy underlying */ function _doHardWork( address strat, uint256[] memory slippages, RewardSlippages memory rewardSlippages ) private { Strategy storage strategy = strategies[strat]; // Check if strategy wasn't exected in current index yet require(strategy.index < globalIndex, "SFIN"); _process(strat, slippages, rewardSlippages.doClaim, rewardSlippages.swapData); } /* ========== DO HARD WORK when REALLOCATING ========== */ /** * @notice Executes do hard work of specified strategies if reallocation is in progress. * * @dev * Requirements: * * - caller must be a valid do hard worker * - provided strategies must be valid * - reallocation is pending for current index * - at least one strategy must be processed * - the system should not be paused * * @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW * @param depositData Reallocation values addressing deposit part of the reallocation DHW * @param allStrategies Array of all strategy addresses in the system for current set reallocation * @param isOneTransaction Flag denoting if the DHW should execute in one transaction */ function batchDoHardWorkReallocation( ReallocationWithdrawData memory withdrawData, ReallocationData memory depositData, address[] memory allStrategies, bool isOneTransaction ) external systemNotPaused onlyDoHardWorker verifyReallocationStrategies(allStrategies) { if (_isBatchComplete()) { globalIndex++; doHardWorksLeft = uint8(allStrategies.length); withdrawalDoHardWorksLeft = uint8(allStrategies.length); } // verify reallocation is set for the current index, and not disabled require( reallocationIndex == globalIndex && reallocationTableHash != 0, "XNRLC" ); // add all indexes if DHW is in one transaction if (isOneTransaction) { require( withdrawData.stratIndexes.length == allStrategies.length && depositData.stratIndexes.length == allStrategies.length, "1TX" ); } else { require(!forceOneTxDoHardWork, "F1TX"); require(withdrawData.stratIndexes.length > 0 || depositData.stratIndexes.length > 0, "NOSTR"); } // execute deposits and withdrawals _batchDoHardWorkReallocation(withdrawData, depositData, allStrategies); // update if DHW for index finished _finishDhw(true); } /** * @notice Executes do hard work of specified strategies if reallocation is in progress. * @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW * @param depositData Reallocation values addressing deposit part of the reallocation DHW * @param allStrategies Array of all strategy addresses in the system for current set reallocation */ function _batchDoHardWorkReallocation( ReallocationWithdrawData memory withdrawData, ReallocationData memory depositData, address[] memory allStrategies ) private { // WITHDRAWALS // reallocation withdraw // process users deposit and withdrawals if (withdrawData.stratIndexes.length > 0) { // check parameters require( withdrawData.stratIndexes.length == withdrawData.slippages.length && withdrawalDoHardWorksLeft >= withdrawData.stratIndexes.length, "BWI" ); // verify if reallocation table matches the reallocationtable hash _verifyReallocationTable(withdrawData.reallocationTable); // get current strategy price data // this is later used to calculate the amount that can me matched // between 2 strategies when they deposit in eachother PriceData[] memory spotPrices = _getPriceData(withdrawData, allStrategies); // process the withdraw part of the reallocation // process the deposit and the withdrawal part of the users deposits/withdrawals _processWithdraw( withdrawData, allStrategies, spotPrices ); // update number of strategies needing to be processed for the current reallocation DHW // can continue to deposit only when it reaches 0 _updateWithdrawalDohardWorksleft(withdrawData.stratIndexes.length); } // check if withdrawal phase was finished before starting deposit require( !(depositData.stratIndexes.length > 0 && withdrawalDoHardWorksLeft > 0), "WNF" ); // DEPOSITS // deposit reallocated amounts withdrawn above into strategies if (depositData.stratIndexes.length > 0) { // check parameters require( doHardWorksLeft >= depositData.stratIndexes.length && depositData.stratIndexes.length == depositData.slippages.length, "BDI" ); // deposit reallocated amounts into strategies // this only deals with the reallocated amounts as users were already processed in the withdrawal phase for (uint128 i = 0; i < depositData.stratIndexes.length; i++) { uint256 stratIndex = depositData.stratIndexes[i]; address stratAddress = allStrategies[stratIndex]; Strategy storage strategy = strategies[stratAddress]; // verify the strategy was not removed (it could be removed in the middle of the DHW if the DHW was executed in multiple transactions) _notRemoved(stratAddress); require(strategy.isInDepositPhase, "SWNP"); // deposit reallocation withdrawn amounts according to the calculations _doHardWorkDeposit(stratAddress, depositData.slippages[stratIndex]); // mark strategy as finished for the current index _finishStrategyDoHardWork(stratAddress); // remove the flag indicating strategy should deposit reallocated amount strategy.isInDepositPhase = false; } // update number of strategies left in the current index // if this reaches 0, DHW is considered complete _updateDoHardWorksLeft(depositData.stratIndexes.length); } } /** * @notice Executes user process and withdraw part of the do-hard-work for the specified strategies when reallocation is in progress. * @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW * @param allStrategies Array of all strategy addresses in the system for current set reallocation * @param spotPrices current strategy share price data, used to calculate the amount that can me matched between 2 strategies when reallcating */ function _processWithdraw( ReallocationWithdrawData memory withdrawData, address[] memory allStrategies, PriceData[] memory spotPrices ) private { // go over reallocation table and calculate what amount of shares can be optimized when reallocating // we can optimize if two strategies deposit into eachother. With the `spotPrices` we can compare the strategy values. ReallocationShares memory reallocation = _optimizeReallocation(withdrawData, spotPrices); // go over withdrawals for (uint256 i = 0; i < withdrawData.stratIndexes.length; i++) { uint256 stratIndex = withdrawData.stratIndexes[i]; address stratAddress = allStrategies[stratIndex]; Strategy storage strategy = strategies[stratAddress]; _notRemoved(stratAddress); require(!strategy.isInDepositPhase, "SWP"); uint128 withdrawnReallocationReceived; { uint128 sharesToWithdraw = reallocation.totalSharesWithdrawn[stratIndex] - reallocation.optimizedShares[stratIndex]; ProcessReallocationData memory processReallocationData = ProcessReallocationData( sharesToWithdraw, reallocation.optimizedShares[stratIndex], reallocation.optimizedWithdraws[stratIndex] ); // withdraw reallocation / returns non-optimized withdrawn amount withdrawnReallocationReceived = _doHardWorkReallocation(stratAddress, withdrawData.slippages[stratIndex], processReallocationData); } // reallocate withdrawn to other strategies _depositReallocatedAmount( reallocation.totalSharesWithdrawn[stratIndex], withdrawnReallocationReceived, reallocation.optimizedWithdraws[stratIndex], allStrategies, withdrawData.reallocationTable[stratIndex] ); _updatePending(stratAddress); strategy.isInDepositPhase = true; } } /** * @notice Process strategy DHW, including reallocation * @dev Only executed when reallocation is set for the DHW * @param strat Strategy address * @param slippages Array of slippage values * @param processReallocationData Reallocation data (see ProcessReallocationData) * @return Received withdrawn reallocation */ function _doHardWorkReallocation( address strat, uint256[] memory slippages, ProcessReallocationData memory processReallocationData ) private returns(uint128){ Strategy storage strategy = strategies[strat]; // Check if strategy wasn't exected in current index yet require(strategy.index < globalIndex, "SFIN"); uint128 withdrawnReallocationReceived = _processReallocation(strat, slippages, processReallocationData); return withdrawnReallocationReceived; } /** * @notice Process deposit collected form the reallocation * @dev Only executed when reallocation is set for the DHW * @param strat Strategy address * @param slippages Array of slippage values */ function _doHardWorkDeposit( address strat, uint256[] memory slippages ) private { _processDeposit(strat, slippages); } /** * @notice Calculate amount of shares that can be swapped between a pair of strategies (without withdrawing from the protocols) * * @dev This is done to ensure only the necessary amoun gets withdrawn from protocols and lower the total slippage and fee. * NOTE: We know strategies depositing into eachother must have the same underlying asset * The underlying asset is used to compare the amount ob both strategies withdrawing (depositing) into eachother. * * Returns: * - amount of optimized collateral amount for each strategy * - amount of optimized shares for each strategy * - total non-optimized amount of shares for each strategy * * @param withdrawData Withdraw data (see WithdrawData) * @param priceData An array of price data (see PriceData) * @return reallocationShares Containing arrays showing the optimized share and underlying token amounts */ function _optimizeReallocation( ReallocationWithdrawData memory withdrawData, PriceData[] memory priceData ) private pure returns (ReallocationShares memory) { // amount of optimized collateral amount for each strategy uint128[] memory optimizedWithdraws = new uint128[](withdrawData.reallocationTable.length); // amount of optimized shares for each strategy uint128[] memory optimizedShares = new uint128[](withdrawData.reallocationTable.length); // total non-optimized amount of shares for each strategy uint128[] memory totalShares = new uint128[](withdrawData.reallocationTable.length); // go over all the strategies (over reallcation table) for (uint128 i = 0; i < withdrawData.reallocationTable.length; i++) { for (uint128 j = i + 1; j < withdrawData.reallocationTable.length; j++) { // check if both strategies are depositing to eachother, if yes - optimize if (withdrawData.reallocationTable[i][j] > 0 && withdrawData.reallocationTable[j][i] > 0) { // calculate strategy I underlying collateral amout withdrawing uint128 amountI = uint128(withdrawData.reallocationTable[i][j] * priceData[i].totalValue / priceData[i].totalShares); // calculate strategy I underlying collateral amout withdrawing uint128 amountJ = uint128(withdrawData.reallocationTable[j][i] * priceData[j].totalValue / priceData[j].totalShares); uint128 optimizedAmount; // check which strategy is withdrawing less if (amountI > amountJ) { optimizedAmount = amountJ; } else { optimizedAmount = amountI; } // use the lesser value of both to save maximum possible optimized amount withdrawing optimizedWithdraws[i] += optimizedAmount; optimizedWithdraws[j] += optimizedAmount; } // sum total shares withdrawing for each strategy unchecked { totalShares[i] += uint128(withdrawData.reallocationTable[i][j]); totalShares[j] += uint128(withdrawData.reallocationTable[j][i]); } } // If we optimized for a strategy, calculate the total shares optimized back from the collateral amount. // The optimized shares amount will never be withdrawn from the strategy, as we know other strategies are // depositing to the strategy in the equal amount and we know how to mach them. if (optimizedWithdraws[i] > 0) { optimizedShares[i] = Math.getProportion128(optimizedWithdraws[i], priceData[i].totalShares, priceData[i].totalValue); } } ReallocationShares memory reallocationShares = ReallocationShares( optimizedWithdraws, optimizedShares, totalShares ); return reallocationShares; } /** * @notice Get urrent strategy price data, containing total balance and total shares * @dev Also verify if the total strategy value is according to the defined values * * @param withdrawData Withdraw data (see WithdrawData) * @param allStrategies Array of strategy addresses * @return Price data (see PriceData) */ function _getPriceData( ReallocationWithdrawData memory withdrawData, address[] memory allStrategies ) private returns(PriceData[] memory) { PriceData[] memory spotPrices = new PriceData[](allStrategies.length); for (uint128 i = 0; i < allStrategies.length; i++) { // claim rewards before getting the price if (withdrawData.rewardSlippages[i].doClaim) { _claimRewards(allStrategies[i], withdrawData.rewardSlippages[i].swapData); } for (uint128 j = 0; j < allStrategies.length; j++) { // if a strategy is withdrawing in reallocation get its spot price if (withdrawData.reallocationTable[i][j] > 0) { // if strategy is removed treat it's value as 0 if (!strategies[allStrategies[i]].isRemoved) { spotPrices[i].totalValue = _getStratValue(allStrategies[i]); } spotPrices[i].totalShares = strategies[allStrategies[i]].totalShares; require( spotPrices[i].totalValue >= withdrawData.priceSlippages[i].min && spotPrices[i].totalValue <= withdrawData.priceSlippages[i].max, "BPRC" ); break; } } } return spotPrices; } /** * @notice Processes reallocated amount deposits. * @param reallocateSharesToWithdraw Reallocate shares to withdraw * @param withdrawnReallocationReceived Received withdrawn reallocation * @param optimizedWithdraw Optimized withdraw * @param _strategies Array of strategy addresses * @param stratReallocationShares Array of strategy reallocation shares */ function _depositReallocatedAmount( uint128 reallocateSharesToWithdraw, uint128 withdrawnReallocationReceived, uint128 optimizedWithdraw, address[] memory _strategies, uint256[] memory stratReallocationShares ) private { for (uint256 i = 0; i < stratReallocationShares.length; i++) { if (stratReallocationShares[i] > 0) { Strategy storage depositStrategy = strategies[_strategies[i]]; // add actual withdrawn deposit depositStrategy.pendingReallocateDeposit += Math.getProportion128(withdrawnReallocationReceived, stratReallocationShares[i], reallocateSharesToWithdraw); // add optimized deposit depositStrategy.pendingReallocateOptimizedDeposit += Math.getProportion128(optimizedWithdraw, stratReallocationShares[i], reallocateSharesToWithdraw); } } } /* ========== SHARED FUNCTIONS ========== */ /** * @notice After strategy DHW is complete increment strategy index * @param strat Strategy address */ function _finishStrategyDoHardWork(address strat) private { Strategy storage strategy = strategies[strat]; strategy.index++; emit DoHardWorkStrategyCompleted(strat, strategy.index); } /** * @notice After strategy DHW process update strategy pending values * @dev set pending next as pending and reset pending next * @param strat Strategy address */ function _updatePending(address strat) private { Strategy storage strategy = strategies[strat]; Pending memory pendingUserNext = strategy.pendingUserNext; strategy.pendingUser = pendingUserNext; if ( pendingUserNext.deposit != Max128Bit.ZERO || pendingUserNext.sharesToWithdraw != Max128Bit.ZERO ) { strategy.pendingUserNext = Pending(Max128Bit.ZERO, Max128Bit.ZERO); } } /** * @notice Update the number of "do hard work" processes left. * @param processedCount Number of completed actions */ function _updateDoHardWorksLeft(uint256 processedCount) private { doHardWorksLeft -= uint8(processedCount); } /** * @notice Update the number of "withdrawal do hard work" processes left. * @param processedCount Number of completed actions */ function _updateWithdrawalDohardWorksleft(uint256 processedCount) private { withdrawalDoHardWorksLeft -= uint8(processedCount); } /** * @notice Hash a reallocation table after it was updated * @param reallocationTable 2D table showing amount of shares withdrawing to each strategy */ function _hashReallocationTable(uint256[][] memory reallocationTable) internal { reallocationTableHash = Hash.hashReallocationTable(reallocationTable); if (logReallocationTable) { // this is only meant to be emitted when debugging emit ReallocationTableUpdatedWithTable(reallocationIndex, reallocationTableHash, reallocationTable); } else { emit ReallocationTableUpdated(reallocationIndex, reallocationTableHash); } } /** * @notice Calculate and store the hash of the given strategy array * @param strategies Strategy addresses to hash */ function _hashReallocationStrategies(address[] memory strategies) internal { reallocationStrategiesHash = Hash.hashStrategies(strategies); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolExternal.sol"; import "./SpoolReallocation.sol"; /** * @notice Exposes spool functions to set and redeem actions. * * @dev * Most of the functions are restricted to vaults. The action is * recorded in the buffer system and is processed at the next * do hard work. * A user cannot interact with any of the Spool functions directly. * * Complete interaction with Spool consists of 4 steps * 1. deposit * 2. redeem shares * 3. withdraw * 4. redeem underlying asset * * Redeems (step 2. and 4.) are done at the same time. Redeem is * processed automatically on first vault interaction after the DHW * is completed. * * As the system works asynchronously, between every step * a do hard work needs to be executed. The shares and actual * withdrawn amount are only calculated at the time of action (DHW). */ abstract contract SpoolExternal is ISpoolExternal, SpoolReallocation { using Bitwise for uint256; using SafeERC20 for IERC20; using Max128Bit for uint128; /* ========== DEPOSIT ========== */ /** * @notice Allows a vault to queue a deposit to a strategy. * * @dev * Requirements: * * - the caller must be a vault * - strategy shouldn't be removed * * @param strat Strategy address to deposit to * @param amount Amount to deposit * @param index Global index vault is depositing at (active global index) */ function deposit(address strat, uint128 amount, uint256 index) external override onlyVault notRemoved(strat) { Strategy storage strategy = strategies[strat]; Pending storage strategyPending = _getStrategyPending(strategy, index); Vault storage vault = strategy.vaults[msg.sender]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; // save to storage strategyPending.deposit = strategyPending.deposit.add(amount); vaultBatch.deposited += amount; } /* ========== WITHDRAW ========== */ /** * @notice Allows a vault to queue a withdrawal from a strategy. * * @dev * Requirements: * * - the caller must be a vault * - strategy shouldn't be removed * * @param strat Strategy address to withdraw from * @param vaultProportion Proportion of all vault-strategy shares a vault wants to withdraw, denoted in basis points (10_000 is 100%) * @param index Global index vault is depositing at (active global index) */ function withdraw(address strat, uint256 vaultProportion, uint256 index) external override onlyVault { Strategy storage strategy = strategies[strat]; Pending storage strategyPending = _getStrategyPending(strategy, index); Vault storage vault = strategy.vaults[msg.sender]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; // calculate new shares to withdraw uint128 sharesToWithdraw = Math.getProportion128(vault.shares, vaultProportion, ACCURACY); // save to storage strategyPending.sharesToWithdraw = strategyPending.sharesToWithdraw.add(sharesToWithdraw); vaultBatch.withdrawnShares += sharesToWithdraw; } /* ========== DEPOSIT/WITHDRAW SHARED ========== */ /** * @notice Get strategy pending struct, depending on if the strategy do hard work has already been executed in the current index * @param strategy Strategy data (see Strategy struct) * @param interactingIndex Global index for which to get the struct * @return pending Storage struct containing all unprocessed deposits and withdrawals for the `interactingIndex` */ function _getStrategyPending(Strategy storage strategy, uint256 interactingIndex) private view returns (Pending storage pending) { // if index we are interacting with (active global index) is same as strategy index, then DHW has already been executed in index if (_isNextStrategyIndex(strategy, interactingIndex)) { pending = strategy.pendingUser; } else { pending = strategy.pendingUserNext; } } /* ========== REDEEM ========== */ /** * @notice Allows a vault to redeem deposit and withdrawals for the processed index. * @dev * * Requirements: * * - the caller must be a valid vault * * @param strat Strategy address * @param index Global index the vault is redeeming for * @return Received vault received shares from the deposit and received vault underlying withdrawn amounts */ function redeem(address strat, uint256 index) external override onlyVault returns (uint128, uint128) { Strategy storage strategy = strategies[strat]; Batch storage batch = strategy.batches[index]; Vault storage vault = strategy.vaults[msg.sender]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; uint128 vaultBatchDeposited = vaultBatch.deposited; uint128 vaultBatchWithdrawnShares = vaultBatch.withdrawnShares; uint128 vaultDepositReceived = 0; uint128 vaultWithdrawnReceived = 0; uint128 vaultShares = vault.shares; // Make calculations if deposit in vault batch was performed if (vaultBatchDeposited > 0 && batch.deposited > 0) { vaultDepositReceived = Math.getProportion128(batch.depositedReceived, vaultBatchDeposited, batch.deposited); // calculate new vault-strategy shares // new shares are calculated at the DHW time, here vault only // takes the proportion of the vault deposit compared to the total deposit vaultShares += Math.getProportion128(batch.depositedSharesReceived, vaultBatchDeposited, batch.deposited); // reset to 0 to get the gas reimbursement vaultBatch.deposited = 0; } // Make calculations if withdraw in vault batch was performed if (vaultBatchWithdrawnShares > 0 && batch.withdrawnShares > 0) { // Withdrawn recieved represents the total underlying a strategy got back after DHW has processed the withdrawn shares. // This is stored at the DHW time, here vault only takes the proportion // of the vault shares withdrwan compared to the total shares withdrawn vaultWithdrawnReceived = Math.getProportion128(batch.withdrawnReceived, vaultBatchWithdrawnShares, batch.withdrawnShares); // substract all the shares withdrawn in the index after collecting the withdrawn recieved vaultShares -= vaultBatchWithdrawnShares; // reset to 0 to get the gas reimbursement vaultBatch.withdrawnShares = 0; } // store the updated shares vault.shares = vaultShares; return (vaultDepositReceived, vaultWithdrawnReceived); } /** * @notice Redeem underlying token * @dev * This function is only called by the vault after the vault redeem is processed * As redeem is called by each strategy separately, we don't want to transfer the * withdrawn underlyin tokens x amount of times. * * Requirements: * - Can only be invoked by vault * * @param amount Amount to redeem */ function redeemUnderlying(uint128 amount) external override onlyVault { IVault(msg.sender).underlying().safeTransfer(msg.sender, amount); } /* ========== REDEEM REALLOCATION ========== */ /** * @notice Redeem vault shares after reallocation has been processed for the vault * @dev * * Requirements: * - Can only be invoked by vault * * @param vaultStrategies Array of vault strategy addresses * @param depositProportions Values representing how the vault has deposited it's withdrawn shares * @param index Index at which the reallocation was perofmed */ function redeemReallocation( address[] memory vaultStrategies, uint256 depositProportions, uint256 index ) external override onlyVault { // count number of strategies we deposit into uint128 depositStratsCount = 0; for (uint256 i = 0; i < vaultStrategies.length; i++) { uint256 prop = depositProportions.get14BitUintByIndex(i); if (prop > 0) { depositStratsCount++; } } // init deposit and withdrawal strategy arrays address[] memory withdrawStrats = new address[](vaultStrategies.length - depositStratsCount); address[] memory depositStrats = new address[](depositStratsCount); uint256[] memory depositProps = new uint256[](depositStratsCount); // fill deposit and withdrawal strategy arrays { uint128 k = 0; uint128 l = 0; for (uint256 i = 0; i < vaultStrategies.length; i++) { uint256 prop = depositProportions.get14BitUintByIndex(i); if (prop > 0) { depositStrats[k] = vaultStrategies[i]; depositProps[k] = prop; k++; } else { withdrawStrats[l] = vaultStrategies[i]; l++; } } } uint256 totalVaultWithdrawnReceived = 0; // calculate total withdrawal amount for (uint256 i = 0; i < withdrawStrats.length; i++) { Strategy storage strategy = strategies[withdrawStrats[i]]; BatchReallocation storage reallocationBatch = strategy.reallocationBatches[index]; Vault storage vault = strategy.vaults[msg.sender]; // if we withdrawed from strategy, claim and spread across deposits uint256 vaultWithdrawnReallocationShares = vault.withdrawnReallocationShares; if (vaultWithdrawnReallocationShares > 0) { // if batch withdrawn shares is 0, reallocation was canceled as a strategy was removed // if so, skip calculation and reset withdrawn reallcoation shares to 0 if (reallocationBatch.withdrawnReallocationShares > 0) { totalVaultWithdrawnReceived += (reallocationBatch.withdrawnReallocationReceived * vaultWithdrawnReallocationShares) / reallocationBatch.withdrawnReallocationShares; // substract the shares withdrawn from in the reallocation vault.shares -= uint128(vaultWithdrawnReallocationShares); } vault.withdrawnReallocationShares = 0; } } // calculate how the withdrawn amount was deposited to the depositing strategies uint256 vaultWithdrawnReceivedLeft = totalVaultWithdrawnReceived; uint256 lastDepositStratIndex = depositStratsCount - 1; for (uint256 i = 0; i < depositStratsCount; i++) { Strategy storage depositStrategy = strategies[depositStrats[i]]; Vault storage depositVault = depositStrategy.vaults[msg.sender]; BatchReallocation storage reallocationBatch = depositStrategy.reallocationBatches[index]; if (reallocationBatch.depositedReallocation > 0) { // calculate reallocation strat deposit amount uint256 depositAmount; // if the strategy is last among the depositing ones, use the amount left to calculate the new shares // (same pattern was used when distributing the withdrawn shares to the depositing strategies - last strategy got what was left of shares) if (i < lastDepositStratIndex) { depositAmount = (totalVaultWithdrawnReceived * depositProps[i]) / FULL_PERCENT; vaultWithdrawnReceivedLeft -= depositAmount; } else { // if strat is last, use deposit left depositAmount = vaultWithdrawnReceivedLeft; } // based on calculated deposited amount calculate/redeem the new strategy shares belonging to a vault depositVault.shares += SafeCast.toUint128((reallocationBatch.depositedReallocationSharesReceived * depositAmount) / reallocationBatch.depositedReallocation); } } } /* ========== FAST WITHDRAW ========== */ /** * @notice Instantly withdraw shares from a strategy and return recieved underlying tokens. * @dev * User can execute the withdrawal of his shares from the vault at any time (except when * the reallocation is pending) without waiting for the DHW to process it. This is done * independently of other events. The gas cost is paid entirely by the user. * Withdrawn amount is sent back to the caller (FastWithdraw) contract, that later on, * sends it to a user. * * Requirements: * * - the caller must be a fast withdraw contract * - strategy shouldn't be removed * * @param strat Strategy address * @param underlying Address of underlying asset * @param shares Amount of shares to withdraw * @param slippages Strategy slippage values verifying the validity of the strategy state * @param swapData Array containig data to swap unclaimed strategy reward tokens for underlying asset * @return Withdrawn Underlying asset withdrarn amount */ function fastWithdrawStrat( address strat, address underlying, uint256 shares, uint256[] memory slippages, SwapData[] memory swapData ) external override onlyFastWithdraw notRemoved(strat) returns(uint128) { // returns withdrawn amount return _fastWithdrawStrat(strat, underlying, shares, slippages, swapData); } /* ========== REMOVE SHARES (prepare for fast withdraw) ========== */ /** * @notice Remove vault shares. * * @dev * Called by the vault when a user requested a fast withdraw * These shares are either withdrawn from the strategies immidiately or * stored as user-strategy shares in the FastWithdraw contract. * * Requirements: * * - can only be called by the vault * * @param vaultStrategies Array of strategy addresses * @param vaultProportion Proportion of all vault-strategy shares a vault wants to remove, denoted in basis points (10_000 is 100%) * @return Array of removed shares per strategy */ function removeShares( address[] memory vaultStrategies, uint256 vaultProportion ) external override onlyVault returns(uint128[] memory) { uint128[] memory removedShares = new uint128[](vaultStrategies.length); for (uint128 i = 0; i < vaultStrategies.length; i++) { _notRemoved(vaultStrategies[i]); Strategy storage strategy = strategies[vaultStrategies[i]]; Vault storage vault = strategy.vaults[msg.sender]; uint128 sharesToWithdraw = Math.getProportion128(vault.shares, vaultProportion, ACCURACY); removedShares[i] = sharesToWithdraw; vault.shares -= sharesToWithdraw; } return removedShares; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolReallocation.sol"; import "./SpoolDoHardWork.sol"; // libraries import "../libraries/Bitwise.sol"; // other imports import "../interfaces/IVault.sol"; /** * @notice Spool part of implementation dealing with the reallocation of assets * * @dev * Allocation provider can update vault allocation across strategies. * This requires vault to withdraw from some and deposit to other strategies. * This happens across multiple vaults. The system handles all vault reallocations * at once and optimizes it between eachother and users. * */ abstract contract SpoolReallocation is ISpoolReallocation, SpoolDoHardWork { using Bitwise for uint256; /* ========== SET REALLOCATION ========== */ /** * @notice Set vaults to reallocate on next do hard work * Requirements: * - Caller must have allocation provider role * - Vaults array must not be empty * - Vaults must be valid * - Strategies must be valid * - If reallocation was already initialized before: * - Reallocation table hash must be set * - Reallocation table must be valid * * @param vaults Array of vault addresses * @param strategies Array of strategy addresses * @param reallocationTable Reallocation details */ function reallocateVaults( VaultData[] memory vaults, address[] memory strategies, uint256[][] memory reallocationTable ) external onlyAllocationProvider { require(vaults.length > 0, "NOVRLC"); uint24 activeGlobalIndex = getActiveGlobalIndex(); // If reallocation was already initialized before, // verify state and parameters before continuing if (reallocationIndex > 0) { // If reallocation was started for index and table hash is 0, // the reallocation was canceled. Prevent from setting it in same index again. require(reallocationTableHash != 0, "RLCSTP"); // check if reallocation can still be set for same global index as before require(reallocationIndex == activeGlobalIndex, "RLCINP"); // verifies strategies agains current reallocation strategies hash _verifyReallocationStrategies(strategies); _verifyReallocationTable(reallocationTable); } else { // if new reallocation, init empty reallocation shares table // verifies all system strategies using Controller contract _verifyStrategies(strategies); // hash and save strategies // this strategies hash is then used to verify strategies during the reallocation // if the strat is exploited and removed from the system, this hash is used to be consistent // with reallocation table ordering as system strategies change. _hashReallocationStrategies(strategies); reallocationIndex = activeGlobalIndex; reallocationTable = new uint256[][](strategies.length); for (uint256 i = 0; i < strategies.length; i++) { reallocationTable[i] = new uint256[](strategies.length); } emit StartReallocation(reallocationIndex); } // loop over vaults for (uint128 i = 0; i < vaults.length; i++) { // check if address is a valid vault _isVault(vaults[i].vault); // reallocate vault //address[] memory vaultStrategies = _buildVaultStrategiesArray(vaults[i].strategiesBitwise, vaults[i].strategiesCount, strategies); (uint256[] memory withdrawProportions, uint256 depositProportions) = IVault(vaults[i].vault).reallocate( _buildVaultStrategiesArray(vaults[i].strategiesBitwise, vaults[i].strategiesCount, strategies), vaults[i].newProportions, getCompletedGlobalIndex(), // NOTE: move to var if call stack not too deeep activeGlobalIndex); // withdraw and deposit from vault strategies for (uint128 j = 0; j < vaults[i].strategiesCount; j++) { if (withdrawProportions[j] > 0) { uint256 withdrawStratIndex = vaults[i].strategiesBitwise.get8BitUintByIndex(j); (uint128 newSharesWithdrawn) = _reallocateVaultStratWithdraw( vaults[i].vault, strategies[withdrawStratIndex], withdrawProportions[j], activeGlobalIndex ); _updateDepositReallocationForStrat( newSharesWithdrawn, vaults[i], depositProportions, reallocationTable[withdrawStratIndex] ); } } } // Hash reallocation proportions _hashReallocationTable(reallocationTable); } /** * @notice Remove shares from strategy to set them for a reallocation * @param vaultAddress Vault address * @param strat Strategy address to remove shares * @param vaultProportion Proportion of all vault-strategy shares a vault wants to reallocate * @param index Global index we're reallocating for * @return newSharesWithdrawn New shares withdrawn fro reallocation */ function _reallocateVaultStratWithdraw( address vaultAddress, address strat, uint256 vaultProportion, uint256 index ) private returns (uint128 newSharesWithdrawn) { Strategy storage strategy = strategies[strat]; Vault storage vault = strategy.vaults[vaultAddress]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; // calculate new shares to withdraw uint128 unwithdrawnVaultShares = vault.shares - vaultBatch.withdrawnShares; // if strategy wasn't executed in current batch yet, also substract unprocessed withdrawal shares in current batch if(!_isNextStrategyIndex(strategy, index)) { VaultBatch storage vaultBatchPrevious = vault.vaultBatches[index - 1]; unwithdrawnVaultShares -= vaultBatchPrevious.withdrawnShares; } // return data newSharesWithdrawn = Math.getProportion128(unwithdrawnVaultShares, vaultProportion, ACCURACY); // save to storage vault.withdrawnReallocationShares = newSharesWithdrawn; } /** * @notice Checks whether the given index is next index for the strategy * @param strategy Strategy data (see Strategy struct) * @param interactingIndex Index to check * @return isNextStrategyIndex True if given index is the next strategy index */ function _isNextStrategyIndex( Strategy storage strategy, uint256 interactingIndex ) internal view returns (bool isNextStrategyIndex) { if (strategy.index + 1 == interactingIndex) { isNextStrategyIndex = true; } } /** * @notice Update deposit reallocation for strategy * @param sharesWithdrawn Withdrawn shares * @param vaultData Vault data (see VaultData struct) * @param depositProportions Deposit proportions * @param stratReallocationTable Strategy reallocation table */ function _updateDepositReallocationForStrat( uint128 sharesWithdrawn, VaultData memory vaultData, uint256 depositProportions, uint256[] memory stratReallocationTable ) private pure { // sharesToDeposit = sharesWithdrawn * deposit_strat% uint128 sharesWithdrawnleft = sharesWithdrawn; uint128 lastDepositedIndex = 0; for (uint128 i = 0; i < vaultData.strategiesCount; i++) { uint256 stratDepositProportion = depositProportions.get14BitUintByIndex(i); if (stratDepositProportion > 0) { uint256 globalStratIndex = vaultData.strategiesBitwise.get8BitUintByIndex(i); uint128 withdrawnSharesForStrat = Math.getProportion128(sharesWithdrawn, stratDepositProportion, FULL_PERCENT); stratReallocationTable[globalStratIndex] += withdrawnSharesForStrat; sharesWithdrawnleft -= withdrawnSharesForStrat; lastDepositedIndex = i; } } // add shares left from rounding error to last deposit strat stratReallocationTable[lastDepositedIndex] += sharesWithdrawnleft; } /* ========== SHARED ========== */ /** * @notice Build vault strategies array from a 256bit word. * @dev Each vault index takes 8bits. * * @param bitwiseAddressIndexes Bitwise address indexes * @param strategiesCount Strategies count * @param strategies Array of strategy addresses * @return vaultStrategies Array of vault strategy addresses */ function _buildVaultStrategiesArray( uint256 bitwiseAddressIndexes, uint8 strategiesCount, address[] memory strategies ) private pure returns(address[] memory vaultStrategies) { vaultStrategies = new address[](strategiesCount); for (uint128 i = 0; i < strategiesCount; i++) { uint256 stratIndex = bitwiseAddressIndexes.get8BitUintByIndex(i); vaultStrategies[i] = strategies[stratIndex]; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolStrategy.sol"; import "./SpoolBase.sol"; // libraries import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../libraries/Max/128Bit.sol"; import "../libraries/Math.sol"; // other imports import "../interfaces/IBaseStrategy.sol"; /** * @notice Spool part of implementation dealing with strategy related processing */ abstract contract SpoolStrategy is ISpoolStrategy, SpoolBase { using SafeERC20 for IERC20; /* ========== VIEWS ========== */ /** * @notice Returns the amount of funds the vault caller has in total * deployed to a particular strategy. * * @dev * Although not set as a view function due to the delegatecall * instructions performed by it, its value can be acquired * without actually executing the function by both off-chain * and on-chain code via simulating the transaction's execution. * * @param strat strategy address * * @return amount */ function getUnderlying(address strat) external override returns (uint128) { Strategy storage strategy = strategies[strat]; uint128 totalStrategyShares = strategy.totalShares; if (totalStrategyShares == 0) return 0; return Math.getProportion128(_totalUnderlying(strat), strategy.vaults[msg.sender].shares, totalStrategyShares); } /** * @notice Returns total strategy underlying value. * @param strat Strategy address * @return Total strategy underlying value */ function getStratUnderlying(address strat) external returns (uint128) { return _totalUnderlying(strat); // deletagecall } /** * @notice Get total vault underlying at index. * * @dev * NOTE: Call ONLY if vault shares are correct for the index. * Meaning vault has just redeemed for this index or this is current index. * * @param strat strategy address * @param index index in total underlying * @return Total vault underlying at index */ function getVaultTotalUnderlyingAtIndex(address strat, uint256 index) external override view returns(uint128) { Strategy storage strategy = strategies[strat]; Vault storage vault = strategy.vaults[msg.sender]; TotalUnderlying memory totalUnderlying = strategy.totalUnderlying[index]; if (totalUnderlying.totalShares > 0) { return Math.getProportion128(totalUnderlying.amount, vault.shares, totalUnderlying.totalShares); } return 0; } /** * @notice Yields the total underlying funds of a strategy. * * @dev * The function is not set as view given that it performs a delegate call * instruction to the strategy. * @param strategy Strategy address * @return Total underlying funds */ function _totalUnderlying(address strategy) internal returns (uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector(IBaseStrategy.getStrategyBalance.selector) ); return abi.decode(data, (uint128)); } /** * @notice Get strategy total underlying balance including rewards * @param strategy Strategy address * @return strategyBaฤance Returns strategy balance with the rewards */ function _getStratValue( address strategy ) internal returns(uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector( IBaseStrategy.getStrategyUnderlyingWithRewards.selector ) ); return abi.decode(data, (uint128)); } /** * @notice Returns pending rewards for a strategy * @param strat Strategy for which to return rewards * @param reward Reward address * @return Pending rewards */ function getPendingRewards(address strat, address reward) external view returns(uint256) { return strategies[strat].pendingRewards[reward]; } /** * @notice Returns strat address in shared strategies mapping for index * @param sharedKey Shared strategies key * @param index Strategy addresses index * @return Strategy address */ function getStratSharedAddress(bytes32 sharedKey, uint256 index) external view returns(address) { return strategiesShared[sharedKey].stratAddresses[index]; } /* ========== MUTATIVE EXTERNAL FUNCTIONS ========== */ /** * @notice Adds and initializes a new strategy * * @dev * Requirements: * * - the caller must be the controller * - reallcation must not be pending * - strategy shouldn't be previously removed * * @param strat Strategy to be added */ function addStrategy(address strat) external override onlyController noPendingReallocation notRemoved(strat) { Strategy storage strategy = strategies[strat]; strategy.index = globalIndex; // init as max zero, so first user interaction will be cheaper (non-zero to non-zero storage change) strategy.pendingUser = Pending(Max128Bit.ZERO, Max128Bit.ZERO); strategy.pendingUserNext = Pending(Max128Bit.ZERO, Max128Bit.ZERO); // initialize strategy specific values _initializeStrategy(strat); } /** * @notice Disables a strategy by liquidating all actively deployed funds * within it to its underlying collateral. * * @dev * This function is invoked whenever a strategy is disabled at the controller * level as an emergency. * * Requirements: * * - the caller must be the controller * - strategy shouldn't be previously removed * * @param strat strategy being disabled * @param skipDisable flag to skip executing strategy specific disable function * NOTE: Should always be false, except if `IBaseStrategy.disable` is failing and there is no other way */ function disableStrategy( address strat, bool skipDisable ) external override onlyController notRemoved(strat) { if (isMidReallocation()) { // when reallocating _disableStrategyWhenReallocating(strat); } else { // no reallocation in progress _disableStrategyNoReallocation(strat); } Strategy storage strategy = strategies[strat]; strategy.isRemoved = true; if (!skipDisable) { _disableStrategy(strat); } else { _skippedDisable[strat] = true; } _awaitingEmergencyWithdraw[strat] = true; } /** * @notice Disable strategy when reallocating * @param strat Strategy to disable */ function _disableStrategyWhenReallocating(address strat) private { Strategy storage strategy = strategies[strat]; if(strategy.index < globalIndex) { // is in withdrawal phase if (!strategy.isInDepositPhase) { // decrease do hard work withdrawals left if (withdrawalDoHardWorksLeft > 0) { withdrawalDoHardWorksLeft--; } } else { // if user withdrawal was already performed, collect withdrawn amount to be emergency withdrawn // NOTE: `strategy.index + 1` has to be used as the strategy index has not increased yet _removeNondistributedWithdrawnReceived(strategy, strategy.index + 1); } _decreaseDoHardWorksLeft(true); // save waiting reallocation deposit to be emergency withdrawn strategy.emergencyPending += strategy.pendingReallocateDeposit; strategy.pendingReallocateDeposit = 0; } } /** * @notice Disable strategy when there is no reallocation * @param strat Strategy to disable */ function _disableStrategyNoReallocation(address strat) private { Strategy storage strategy = strategies[strat]; // check if the strategy has already been processed in ongoing do hard work if (strategy.index < globalIndex) { _decreaseDoHardWorksLeft(false); } else if (!_isBatchComplete()) { // if user withdrawal was already performed, collect withdrawn amount to be emergency withdrawn _removeNondistributedWithdrawnReceived(strategy, strategy.index); } // if reallocation is set to be processed, reset reallocation table to cancel it for set index if (reallocationTableHash != 0) { reallocationTableHash = 0; } } /** * @notice Decrease "do hard work" actions left * @notice isMidReallocation Whether system is mid-reallocation */ function _decreaseDoHardWorksLeft(bool isMidReallocation) private { if (doHardWorksLeft > 0) { doHardWorksLeft--; // check if this was last strategy, to complete the do hard work _finishDhw(isMidReallocation); } } /** * @notice Removes the nondistributed amounts recieved, if any * @dev used when emergency withdrawing * * @param strategy Strategy address * @param index index remove from */ function _removeNondistributedWithdrawnReceived(Strategy storage strategy, uint256 index) private { strategy.emergencyPending += strategy.batches[index].withdrawnReceived; strategy.batches[index].withdrawnReceived = 0; strategy.totalUnderlying[index].amount = 0; } /** * @notice Liquidating all actively deployed funds within a strategy after it was disabled. * * @dev * Requirements: * * - the caller must be the controller * - the strategy must be disabled * - the strategy must be awaiting emergency withdraw * * @param strat strategy being disabled * @param data data to perform the withdrawal * @param withdrawRecipient recipient of the withdrawn funds */ function emergencyWithdraw( address strat, address withdrawRecipient, uint256[] memory data ) external override onlyController onlyRemoved(strat) { if (_awaitingEmergencyWithdraw[strat]) { _emergencyWithdraw(strat, withdrawRecipient, data); _awaitingEmergencyWithdraw[strat] = false; } else if (strategies[strat].emergencyPending > 0) { IBaseStrategy(strat).underlying().transfer(withdrawRecipient, strategies[strat].emergencyPending); strategies[strat].emergencyPending = 0; } } /** * @notice Runs strategy specific disable function if it was skipped when disabling the strategy. * Requirements: * - the caller must be the controller * - the strategy must be disabled * * @param strat Strategy to remove */ function runDisableStrategy(address strat) external override onlyController onlyRemoved(strat) { require(_skippedDisable[strat], "SDEX"); _disableStrategy(strat); _skippedDisable[strat] = false; } /* ========== MUTATIVE INTERNAL FUNCTIONS ========== */ /** * @notice Invokes the process function on the strategy to process teh pending actions * @dev executed deposit or withdrawal and compound of the reward tokens * * @param strategy Strategy address * @param slippages Array of slippage parameters to apply when depositing or withdrawing * @param harvestRewards Whether to harvest (swap and deposit) strategy rewards or not * @param swapData Array containig data to swap unclaimed strategy reward tokens for underlying asset */ function _process( address strategy, uint256[] memory slippages, bool harvestRewards, SwapData[] memory swapData ) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.process.selector, slippages, harvestRewards, swapData ) ); } /** * @notice Invoke process reallocation for a strategy * @dev This is the first par of the strategy DHW when reallocating * * @param strategy Strategy address * @param slippages Array of slippage parameters to apply when withdrawing * @param processReallocationData Reallocation values used when processing * @return withdrawnUnderlying Actual withdrawn reallocation underlying assets received */ function _processReallocation( address strategy, uint256[] memory slippages, ProcessReallocationData memory processReallocationData ) internal returns(uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector( IBaseStrategy.processReallocation.selector, slippages, processReallocationData ) ); // return actual withdrawn reallocation underlying assets received return abi.decode(data, (uint128)); } /** * @notice Invoke process deposit for a strategy * @param strategy Strategy address * @param slippages Array of slippage parameters to apply when depositing */ function _processDeposit( address strategy, uint256[] memory slippages ) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.processDeposit.selector, slippages ) ); } /** * @notice Invoke fast withdraw for a strategy * @param strategy Strategy to withdraw from * @param underlying Asset to withdraw * @param shares Amount of shares to withdraw * @param slippages Array of slippage parameters to apply when withdrawing * @param swapData Swap slippage and path array * @return Withdrawn amount */ function _fastWithdrawStrat( address strategy, address underlying, uint256 shares, uint256[] memory slippages, SwapData[] memory swapData ) internal returns(uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector( IBaseStrategy.fastWithdraw.selector, shares, slippages, swapData ) ); (uint128 withdrawnAmount) = abi.decode(data, (uint128)); IERC20(underlying).safeTransfer(msg.sender, withdrawnAmount); return withdrawnAmount; } /** * @notice Invoke claim rewards for a strategy * @param strategy Strategy address * @param swapData Swap slippage and path */ function _claimRewards( address strategy, SwapData[] memory swapData ) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.claimRewards.selector, swapData ) ); } /** * @notice Invokes the emergencyWithdraw function on a strategy * @param strategy Strategy to which to relay the call to * @param recipient Address to which to withdraw to * @param data Strategy specific data to perorm energency withdraw on a strategy */ function _emergencyWithdraw(address strategy, address recipient, uint256[] memory data) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.emergencyWithdraw.selector, recipient, data ) ); } /** * @notice Initializes strategy specific values * @param strategy Strategy to initialize */ function _initializeStrategy(address strategy) internal { _relay( strategy, abi.encodeWithSelector(IBaseStrategy.initialize.selector) ); } /** * @notice Cleans strategy specific values after disabling * @param strategy Strategy to disable */ function _disableStrategy(address strategy) internal { _relay( strategy, abi.encodeWithSelector(IBaseStrategy.disable.selector) ); } }
Decode revert message _returnData Data returned by delegatecall return Revert string/ if the _res length is less than 68, then the transaction failed silently (without a revert message) slice the sig hash
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { if (_returnData.length < 68) return "SILENT"; assembly { _returnData := add(_returnData, 0x04) } }
11,832,637
// SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./interfaces/INodeOperatorRegistry.sol"; import "./interfaces/IValidatorFactory.sol"; import "./interfaces/IValidator.sol"; import "./interfaces/IStMATIC.sol"; /// @title NodeOperatorRegistry /// @author 2021 ShardLabs. /// @notice NodeOperatorRegistry is the main contract that manage validators /// @dev NodeOperatorRegistry is the main contract that manage operators. contract NodeOperatorRegistry is INodeOperatorRegistry, PausableUpgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable { enum NodeOperatorStatus { INACTIVE, ACTIVE, STOPPED, UNSTAKED, CLAIMED, EXIT, JAILED, EJECTED } /// @notice The node operator struct /// @param status node operator status(INACTIVE, ACTIVE, STOPPED, CLAIMED, UNSTAKED, EXIT, JAILED, EJECTED). /// @param name node operator name. /// @param rewardAddress Validator public key used for access control and receive rewards. /// @param validatorId validator id of this node operator on the polygon stake manager. /// @param signerPubkey public key used on heimdall. /// @param validatorShare validator share contract used to delegate for on polygon. /// @param validatorProxy the validator proxy, the owner of the validator. /// @param commissionRate the commission rate applied by the operator on polygon. /// @param maxDelegateLimit max delegation limit that StMatic contract will delegate to this operator each time delegate function is called. struct NodeOperator { NodeOperatorStatus status; string name; address rewardAddress; bytes signerPubkey; address validatorShare; address validatorProxy; uint256 validatorId; uint256 commissionRate; uint256 maxDelegateLimit; } /// @notice all the roles. bytes32 public constant REMOVE_OPERATOR_ROLE = keccak256("LIDO_REMOVE_OPERATOR"); bytes32 public constant PAUSE_OPERATOR_ROLE = keccak256("LIDO_PAUSE_OPERATOR"); bytes32 public constant DAO_ROLE = keccak256("LIDO_DAO"); /// @notice contract version. string public version; /// @notice total node operators. uint256 private totalNodeOperators; /// @notice validatorFactory address. address private validatorFactory; /// @notice stakeManager address. address private stakeManager; /// @notice polygonERC20 token (Matic) address. address private polygonERC20; /// @notice stMATIC address. address private stMATIC; /// @notice keeps track of total number of operators uint256 nodeOperatorCounter; /// @notice min amount allowed to stake per validator. uint256 public minAmountStake; /// @notice min HeimdallFees allowed to stake per validator. uint256 public minHeimdallFees; /// @notice commision rate applied to all the operators. uint256 public commissionRate; /// @notice allows restake. bool public allowsRestake; /// @notice default max delgation limit. uint256 public defaultMaxDelegateLimit; /// @notice This stores the operators ids. uint256[] private operatorIds; /// @notice Mapping of all owners with node operator id. Mapping is used to be able to /// extend the struct. mapping(address => uint256) private operatorOwners; /// @notice Mapping of all node operators. Mapping is used to be able to extend the struct. mapping(uint256 => NodeOperator) private operators; /// --------------------------- Modifiers----------------------------------- /// @notice Check if the msg.sender has permission. /// @param _role role needed to call function. modifier userHasRole(bytes32 _role) { checkCondition(hasRole(_role, msg.sender), "unauthorized"); _; } /// @notice Check if the amount is inbound. /// @param _amount amount to stake. modifier checkStakeAmount(uint256 _amount) { checkCondition(_amount >= minAmountStake, "Invalid amount"); _; } /// @notice Check if the heimdall fee is inbound. /// @param _heimdallFee heimdall fee. modifier checkHeimdallFees(uint256 _heimdallFee) { checkCondition(_heimdallFee >= minHeimdallFees, "Invalid fees"); _; } /// @notice Check if the maxDelegateLimit is less or equal to 10 Billion. /// @param _maxDelegateLimit max delegate limit. modifier checkMaxDelegationLimit(uint256 _maxDelegateLimit) { checkCondition( _maxDelegateLimit <= 10000000000 ether, "Max amount <= 10B" ); _; } /// @notice Check if the rewardAddress is already used. /// @param _rewardAddress new reward address. modifier checkIfRewardAddressIsUsed(address _rewardAddress) { checkCondition( operatorOwners[_rewardAddress] == 0 && _rewardAddress != address(0), "Address used" ); _; } /// -------------------------- initialize ---------------------------------- /// @notice Initialize the NodeOperator contract. function initialize( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ) external initializer { __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); validatorFactory = _validatorFactory; stakeManager = _stakeManager; polygonERC20 = _polygonERC20; stMATIC = _stMATIC; minAmountStake = 10 * 10**18; minHeimdallFees = 20 * 10**18; defaultMaxDelegateLimit = 10 ether; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(REMOVE_OPERATOR_ROLE, msg.sender); _setupRole(PAUSE_OPERATOR_ROLE, msg.sender); _setupRole(DAO_ROLE, msg.sender); } /// ----------------------------- API -------------------------------------- /// @notice Add a new node operator to the system. /// @dev The operator life cycle starts when we call the addOperator /// func allows adding a new operator. During this call, a new validatorProxy is /// deployed by the ValidatorFactory which we can use later to interact with the /// Polygon StakeManager. At the end of this call, the status of the operator /// will be INACTIVE. /// @param _name the node operator name. /// @param _rewardAddress address used for ACL and receive rewards. /// @param _signerPubkey public key used on heimdall len 64 bytes. function addOperator( string memory _name, address _rewardAddress, bytes memory _signerPubkey ) external override whenNotPaused userHasRole(DAO_ROLE) checkIfRewardAddressIsUsed(_rewardAddress) { nodeOperatorCounter++; address validatorProxy = IValidatorFactory(validatorFactory).create(); operators[nodeOperatorCounter] = NodeOperator({ status: NodeOperatorStatus.INACTIVE, name: _name, rewardAddress: _rewardAddress, validatorId: 0, signerPubkey: _signerPubkey, validatorShare: address(0), validatorProxy: validatorProxy, commissionRate: commissionRate, maxDelegateLimit: defaultMaxDelegateLimit }); operatorIds.push(nodeOperatorCounter); totalNodeOperators++; operatorOwners[_rewardAddress] = nodeOperatorCounter; emit AddOperator(nodeOperatorCounter); } /// @notice Allows to stop an operator from the system. /// @param _operatorId the node operator id. function stopOperator(uint256 _operatorId) external override { (, NodeOperator storage no) = getOperator(_operatorId); require( no.rewardAddress == msg.sender || hasRole(DAO_ROLE, msg.sender), "unauthorized" ); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE || status == NodeOperatorStatus.JAILED , "Invalid status"); if (status == NodeOperatorStatus.INACTIVE) { no.status = NodeOperatorStatus.EXIT; } else { IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare); no.status = NodeOperatorStatus.STOPPED; } emit StopOperator(_operatorId); } /// @notice Allows to remove an operator from the system.when the operator status is /// set to EXIT the GOVERNANCE can call the removeOperator func to delete the operator, /// and the validatorProxy used to interact with the Polygon stakeManager. /// @param _operatorId the node operator id. function removeOperator(uint256 _operatorId) external override whenNotPaused userHasRole(REMOVE_OPERATOR_ROLE) { (, NodeOperator storage no) = getOperator(_operatorId); checkCondition(no.status == NodeOperatorStatus.EXIT, "Invalid status"); // update the operatorIds array by removing the operator id. for (uint256 idx = 0; idx < operatorIds.length - 1; idx++) { if (_operatorId == operatorIds[idx]) { operatorIds[idx] = operatorIds[operatorIds.length - 1]; break; } } operatorIds.pop(); totalNodeOperators--; IValidatorFactory(validatorFactory).remove(no.validatorProxy); delete operatorOwners[no.rewardAddress]; delete operators[_operatorId]; emit RemoveOperator(_operatorId); } /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. function joinOperator() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.INACTIVE, "Invalid status" ); IStakeManager sm = IStakeManager(stakeManager); uint256 validatorId = sm.getValidatorId(msg.sender); checkCondition(validatorId != 0, "ValidatorId=0"); IStakeManager.Validator memory poValidator = sm.validators(validatorId); checkCondition( poValidator.contractAddress != address(0), "Validator has no ValidatorShare" ); checkCondition( (poValidator.status == IStakeManager.Status.Active ) && poValidator.deactivationEpoch == 0 , "Validator isn't ACTIVE" ); checkCondition( poValidator.signer == address(uint160(uint256(keccak256(no.signerPubkey)))), "Invalid Signer" ); IValidator(no.validatorProxy).join( validatorId, sm.NFTContract(), msg.sender, no.commissionRate, stakeManager ); no.validatorId = validatorId; address validatorShare = sm.getValidatorContract(validatorId); no.validatorShare = validatorShare; emit JoinOperator(operatorId); } /// ------------------------Stake Manager API------------------------------- /// @notice Allows to stake a validator on the Polygon stakeManager contract. /// @dev The stake func allows each operator's owner to stake, but before that, /// the owner has to approve the amount + Heimdall fees to the ValidatorProxy. /// At the end of this call, the status of the operator is set to ACTIVE. /// @param _amount amount to stake. /// @param _heimdallFee heimdall fees. function stake(uint256 _amount, uint256 _heimdallFee) external override whenNotPaused checkStakeAmount(_amount) checkHeimdallFees(_heimdallFee) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.INACTIVE, "Invalid status" ); (uint256 validatorId, address validatorShare) = IValidator( no.validatorProxy ).stake( msg.sender, _amount, _heimdallFee, true, no.signerPubkey, no.commissionRate, stakeManager, polygonERC20 ); no.validatorId = validatorId; no.validatorShare = validatorShare; emit StakeOperator(operatorId, _amount, _heimdallFee); } /// @notice Allows to restake Matics to Polygon stakeManager /// @dev restake allows an operator's owner to increase the total staked amount /// on Polygon. The owner has to approve the amount to the ValidatorProxy then make /// a call. /// @param _amount amount to stake. function restake(uint256 _amount, bool _restakeRewards) external override whenNotPaused { checkCondition(allowsRestake, "Restake is disabled"); if (_amount == 0) { revert("Amount is ZERO"); } (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); IValidator(no.validatorProxy).restake( msg.sender, no.validatorId, _amount, _restakeRewards, stakeManager, polygonERC20 ); emit RestakeOperator(operatorId, _amount, _restakeRewards); } /// @notice Unstake a validator from the Polygon stakeManager contract. /// @dev when the operators's owner wants to quite the PoLido protocol he can call /// the unstake func, in this case, the operator status is set to UNSTAKED. function unstake() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.JAILED || status == NodeOperatorStatus.EJECTED, "Invalid status" ); if (status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).unstake(no.validatorId, stakeManager); } _unstake(operatorId, no); } /// @notice The DAO unstake the operator if it was unstaked by the stakeManager. /// @dev when the operator was unstaked by the stage Manager the DAO can use this /// function to update the operator status and also withdraw the delegated tokens, /// without waiting for the owner to call the unstake function /// @param _operatorId operator id. function unstake(uint256 _operatorId) external userHasRole(DAO_ROLE) { NodeOperator storage no = operators[_operatorId]; NodeOperatorStatus status = getOperatorStatus(no); checkCondition(status == NodeOperatorStatus.EJECTED, "Invalid status"); _unstake(_operatorId, no); } function _unstake(uint256 _operatorId, NodeOperator storage no) private whenNotPaused { IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare); no.status = NodeOperatorStatus.UNSTAKED; emit UnstakeOperator(_operatorId); } /// @notice Allows the operator's owner to migrate the validator ownership to rewardAddress. /// This can be done only in the case where this operator was stopped by the DAO. function migrate() external override nonReentrant { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition(no.status == NodeOperatorStatus.STOPPED, "Invalid status"); IValidator(no.validatorProxy).migrate( no.validatorId, IStakeManager(stakeManager).NFTContract(), no.rewardAddress ); no.status = NodeOperatorStatus.EXIT; emit MigrateOperator(operatorId); } /// @notice Allows to unjail the validator and turn his status from UNSTAKED to ACTIVE. /// @dev when an operator is JAILED the owner can switch back and stake the /// operator by calling the unjail func, in this case, the operator status is set /// to back ACTIVE. function unjail() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.JAILED, "Invalid status" ); IValidator(no.validatorProxy).unjail(no.validatorId, stakeManager); emit Unjail(operatorId); } /// @notice Allows to top up heimdall fees. /// @dev the operator's owner can topUp the heimdall fees by calling the /// topUpForFee, but before that node operator needs to approve the amount of heimdall /// fees to his validatorProxy. /// @param _heimdallFee amount function topUpForFee(uint256 _heimdallFee) external override whenNotPaused checkHeimdallFees(_heimdallFee) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); IValidator(no.validatorProxy).topUpForFee( msg.sender, _heimdallFee, stakeManager, polygonERC20 ); emit TopUpHeimdallFees(operatorId, _heimdallFee); } /// @notice Allows to unstake staked tokens after withdraw delay. /// @dev after the unstake the operator and waiting for the Polygon withdraw_delay /// the owner can transfer back his staked balance by calling /// unsttakeClaim, after that the operator status is set to CLAIMED function unstakeClaim() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.UNSTAKED, "Invalid status" ); uint256 amount = IValidator(no.validatorProxy).unstakeClaim( no.validatorId, msg.sender, stakeManager, polygonERC20 ); no.status = NodeOperatorStatus.CLAIMED; emit UnstakeClaim(operatorId, amount); } /// @notice Allows withdraw heimdall fees /// @dev the operator's owner can claim the heimdall fees. /// func, after that the operator status is set to EXIT. /// @param _accumFeeAmount accumulated heimdall fees /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( no.status == NodeOperatorStatus.CLAIMED, "Invalid status" ); IValidator(no.validatorProxy).claimFee( _accumFeeAmount, _index, _proof, no.rewardAddress, stakeManager, polygonERC20 ); no.status = NodeOperatorStatus.EXIT; emit ClaimFee(operatorId); } /// @notice Allows the operator's owner to withdraw rewards. function withdrawRewards() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); address rewardAddress = no.rewardAddress; uint256 rewards = IValidator(no.validatorProxy).withdrawRewards( no.validatorId, rewardAddress, stakeManager, polygonERC20 ); emit WithdrawRewards(operatorId, rewardAddress, rewards); } /// @notice Allows the operator's owner to update signer publickey. /// @param _signerPubkey new signer publickey function updateSigner(bytes memory _signerPubkey) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); if (no.status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).updateSigner( no.validatorId, _signerPubkey, stakeManager ); } no.signerPubkey = _signerPubkey; emit UpdateSignerPubkey(operatorId); } /// @notice Allows the operator owner to update the name. /// @param _name new operator name. function setOperatorName(string memory _name) external override whenNotPaused { // uint256 operatorId = getOperatorId(msg.sender); // NodeOperator storage no = operators[operatorId]; (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); no.name = _name; emit NewName(operatorId, _name); } /// @notice Allows the operator owner to update the rewardAddress. /// @param _rewardAddress new reward address. function setOperatorRewardAddress(address _rewardAddress) external override whenNotPaused checkIfRewardAddressIsUsed(_rewardAddress) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); no.rewardAddress = _rewardAddress; operatorOwners[_rewardAddress] = operatorId; delete operatorOwners[msg.sender]; emit NewRewardAddress(operatorId, _rewardAddress); } /// -------------------------------DAO-------------------------------------- /// @notice Allows the DAO to set the operator defaultMaxDelegateLimit. /// @param _defaultMaxDelegateLimit default max delegation amount. function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit) external override userHasRole(DAO_ROLE) checkMaxDelegationLimit(_defaultMaxDelegateLimit) { defaultMaxDelegateLimit = _defaultMaxDelegateLimit; } /// @notice Allows the DAO to set the operator maxDelegateLimit. /// @param _operatorId operator id. /// @param _maxDelegateLimit max amount to delegate . function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit) external override userHasRole(DAO_ROLE) checkMaxDelegationLimit(_maxDelegateLimit) { (, NodeOperator storage no) = getOperator(_operatorId); no.maxDelegateLimit = _maxDelegateLimit; } /// @notice Allows to set the commission rate used. function setCommissionRate(uint256 _commissionRate) external override userHasRole(DAO_ROLE) { commissionRate = _commissionRate; } /// @notice Allows the dao to update commission rate for an operator. /// @param _operatorId id of the operator /// @param _newCommissionRate new commission rate function updateOperatorCommissionRate( uint256 _operatorId, uint256 _newCommissionRate ) external override userHasRole(DAO_ROLE) { (, NodeOperator storage no) = getOperator(_operatorId); checkCondition( no.rewardAddress != address(0) || no.status == NodeOperatorStatus.ACTIVE, "Invalid status" ); if (no.status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).updateCommissionRate( no.validatorId, _newCommissionRate, stakeManager ); } no.commissionRate = _newCommissionRate; emit UpdateCommissionRate(_operatorId, _newCommissionRate); } /// @notice Allows to update the stake amount and heimdall fees /// @param _minAmountStake min amount to stake /// @param _minHeimdallFees min amount of heimdall fees function setStakeAmountAndFees( uint256 _minAmountStake, uint256 _minHeimdallFees ) external override userHasRole(DAO_ROLE) checkStakeAmount(_minAmountStake) checkHeimdallFees(_minHeimdallFees) { minAmountStake = _minAmountStake; minHeimdallFees = _minHeimdallFees; } /// @notice Allows to pause the contract. function togglePause() external override userHasRole(PAUSE_OPERATOR_ROLE) { paused() ? _unpause() : _pause(); } /// @notice Allows to toggle restake. function setRestake(bool _restake) external override userHasRole(DAO_ROLE) { allowsRestake = _restake; } /// @notice Allows to set the StMATIC contract address. function setStMATIC(address _stMATIC) external override userHasRole(DAO_ROLE) { stMATIC = _stMATIC; } /// @notice Allows to set the validator factory contract address. function setValidatorFactory(address _validatorFactory) external override userHasRole(DAO_ROLE) { validatorFactory = _validatorFactory; } /// @notice Allows to set the stake manager contract address. function setStakeManager(address _stakeManager) external override userHasRole(DAO_ROLE) { stakeManager = _stakeManager; } /// @notice Allows to set the contract version. /// @param _version contract version function setVersion(string memory _version) external override userHasRole(DEFAULT_ADMIN_ROLE) { version = _version; } /// @notice Allows to get a node operator by msg.sender. /// @param _owner a valid address of an operator owner, if not set msg.sender will be used. /// @return op returns a node operator. function getNodeOperator(address _owner) external view returns (NodeOperator memory) { uint256 operatorId = operatorOwners[_owner]; return _getNodeOperator(operatorId); } /// @notice Allows to get a node operator by _operatorId. /// @param _operatorId the id of the operator. /// @return op returns a node operator. function getNodeOperator(uint256 _operatorId) external view returns (NodeOperator memory) { return _getNodeOperator(_operatorId); } function _getNodeOperator(uint256 _operatorId) private view returns (NodeOperator memory) { (, NodeOperator memory nodeOperator) = getOperator(_operatorId); nodeOperator.status = getOperatorStatus(nodeOperator); return nodeOperator; } function getOperatorStatus(NodeOperator memory _op) private view returns (NodeOperatorStatus res) { if (_op.status == NodeOperatorStatus.STOPPED) { res = NodeOperatorStatus.STOPPED; } else if (_op.status == NodeOperatorStatus.CLAIMED) { res = NodeOperatorStatus.CLAIMED; } else if (_op.status == NodeOperatorStatus.EXIT) { res = NodeOperatorStatus.EXIT; } else if (_op.status == NodeOperatorStatus.UNSTAKED) { res = NodeOperatorStatus.UNSTAKED; } else { IStakeManager.Validator memory v = IStakeManager(stakeManager) .validators(_op.validatorId); if ( v.status == IStakeManager.Status.Active && v.deactivationEpoch == 0 ) { res = NodeOperatorStatus.ACTIVE; } else if ( ( v.status == IStakeManager.Status.Active || v.status == IStakeManager.Status.Locked ) && v.deactivationEpoch != 0 ) { res = NodeOperatorStatus.EJECTED; } else if ( v.status == IStakeManager.Status.Locked && v.deactivationEpoch == 0 ) { res = NodeOperatorStatus.JAILED; } else { res = NodeOperatorStatus.INACTIVE; } } } /// @notice Allows to get a validator share address. /// @param _operatorId the id of the operator. /// @return va returns a stake manager validator. function getValidatorShare(uint256 _operatorId) external view returns (address) { (, NodeOperator memory op) = getOperator(_operatorId); return op.validatorShare; } /// @notice Allows to get a validator from stake manager. /// @param _operatorId the id of the operator. /// @return va returns a stake manager validator. function getValidator(uint256 _operatorId) external view returns (IStakeManager.Validator memory va) { (, NodeOperator memory op) = getOperator(_operatorId); va = IStakeManager(stakeManager).validators(op.validatorId); } /// @notice Allows to get a validator from stake manager. /// @param _owner user address. /// @return va returns a stake manager validator. function getValidator(address _owner) external view returns (IStakeManager.Validator memory va) { (, NodeOperator memory op) = getOperator(operatorOwners[_owner]); va = IStakeManager(stakeManager).validators(op.validatorId); } /// @notice Get the stMATIC contract addresses function getContracts() external view override returns ( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ) { _validatorFactory = validatorFactory; _stakeManager = stakeManager; _polygonERC20 = polygonERC20; _stMATIC = stMATIC; } /// @notice Get the global state function getState() external view override returns ( uint256 _totalNodeOperator, uint256 _totalInactiveNodeOperator, uint256 _totalActiveNodeOperator, uint256 _totalStoppedNodeOperator, uint256 _totalUnstakedNodeOperator, uint256 _totalClaimedNodeOperator, uint256 _totalExitNodeOperator, uint256 _totalJailedNodeOperator, uint256 _totalEjectedNodeOperator ) { uint256 operatorIdsLength = operatorIds.length; _totalNodeOperator = operatorIdsLength; for (uint256 idx = 0; idx < operatorIdsLength; idx++) { uint256 operatorId = operatorIds[idx]; NodeOperator memory op = operators[operatorId]; NodeOperatorStatus status = getOperatorStatus(op); if (status == NodeOperatorStatus.INACTIVE) { _totalInactiveNodeOperator++; } else if (status == NodeOperatorStatus.ACTIVE) { _totalActiveNodeOperator++; } else if (status == NodeOperatorStatus.STOPPED) { _totalStoppedNodeOperator++; } else if (status == NodeOperatorStatus.UNSTAKED) { _totalUnstakedNodeOperator++; } else if (status == NodeOperatorStatus.CLAIMED) { _totalClaimedNodeOperator++; } else if (status == NodeOperatorStatus.JAILED) { _totalJailedNodeOperator++; } else if (status == NodeOperatorStatus.EJECTED) { _totalEjectedNodeOperator++; } else { _totalExitNodeOperator++; } } } /// @notice Get operatorIds. function getOperatorIds() external view override returns (uint256[] memory) { return operatorIds; } /// @notice Returns an operatorInfo list. /// @param _allWithStake if true return all operators with ACTIVE, EJECTED, JAILED. /// @param _delegation if true return all operators that delegation is set to true. /// @return Returns a list of operatorInfo. function getOperatorInfos( bool _delegation, bool _allWithStake ) external view override returns (Operator.OperatorInfo[] memory) { Operator.OperatorInfo[] memory operatorInfos = new Operator.OperatorInfo[]( totalNodeOperators ); uint256 length = operatorIds.length; uint256 index; for (uint256 idx = 0; idx < length; idx++) { uint256 operatorId = operatorIds[idx]; NodeOperator storage no = operators[operatorId]; NodeOperatorStatus status = getOperatorStatus(no); // if operator status is not ACTIVE we continue. But, if _allWithStake is true // we include EJECTED and JAILED operators. if ( status != NodeOperatorStatus.ACTIVE && !(_allWithStake && (status == NodeOperatorStatus.EJECTED || status == NodeOperatorStatus.JAILED)) ) continue; // if true we check if the operator delegation is true. if (_delegation) { if (!IValidatorShare(no.validatorShare).delegation()) continue; } operatorInfos[index] = Operator.OperatorInfo({ operatorId: operatorId, validatorShare: no.validatorShare, maxDelegateLimit: no.maxDelegateLimit, rewardAddress: no.rewardAddress }); index++; } if (index != totalNodeOperators) { Operator.OperatorInfo[] memory operatorInfosOut = new Operator.OperatorInfo[](index); for (uint256 i = 0; i < index; i++) { operatorInfosOut[i] = operatorInfos[i]; } return operatorInfosOut; } return operatorInfos; } /// @notice Checks condition and displays the message /// @param _condition a condition /// @param _message message to display function checkCondition(bool _condition, string memory _message) private pure { require(_condition, _message); } /// @notice Retrieve the operator struct based on the operatorId /// @param _operatorId id of the operator /// @return NodeOperator structure function getOperator(uint256 _operatorId) private view returns (uint256, NodeOperator storage) { if (_operatorId == 0) { _operatorId = getOperatorId(msg.sender); } NodeOperator storage no = operators[_operatorId]; require(no.rewardAddress != address(0), "Operator not found"); return (_operatorId, no); } /// @notice Retrieve the operator struct based on the operator owner address /// @param _user address of the operator owner /// @return NodeOperator structure function getOperatorId(address _user) private view returns (uint256) { uint256 operatorId = operatorOwners[_user]; checkCondition(operatorId != 0, "Operator not found"); return operatorId; } /// -------------------------------Events----------------------------------- /// @notice A new node operator was added. /// @param operatorId node operator id. event AddOperator(uint256 operatorId); /// @notice A new node operator joined. /// @param operatorId node operator id. event JoinOperator(uint256 operatorId); /// @notice A node operator was removed. /// @param operatorId node operator id. event RemoveOperator(uint256 operatorId); /// @param operatorId node operator id. event StopOperator(uint256 operatorId); /// @param operatorId node operator id. event MigrateOperator(uint256 operatorId); /// @notice A node operator was staked. /// @param operatorId node operator id. event StakeOperator( uint256 operatorId, uint256 amount, uint256 heimdallFees ); /// @notice A node operator restaked. /// @param operatorId node operator id. /// @param amount amount to restake. /// @param restakeRewards restake rewards. event RestakeOperator( uint256 operatorId, uint256 amount, bool restakeRewards ); /// @notice A node operator was unstaked. /// @param operatorId node operator id. event UnstakeOperator(uint256 operatorId); /// @notice TopUp heimadall fees. /// @param operatorId node operator id. /// @param amount amount. event TopUpHeimdallFees(uint256 operatorId, uint256 amount); /// @notice Withdraw rewards. /// @param operatorId node operator id. /// @param rewardAddress reward address. /// @param amount amount. event WithdrawRewards( uint256 operatorId, address rewardAddress, uint256 amount ); /// @notice claims unstake. /// @param operatorId node operator id. /// @param amount amount. event UnstakeClaim(uint256 operatorId, uint256 amount); /// @notice update signer publickey. /// @param operatorId node operator id. event UpdateSignerPubkey(uint256 operatorId); /// @notice claim herimdall fee. /// @param operatorId node operator id. event ClaimFee(uint256 operatorId); /// @notice update commission rate. event UpdateCommissionRate(uint256 operatorId, uint256 newCommissionRate); /// @notice Unjail a validator. event Unjail(uint256 operatorId); /// @notice update operator name. event NewName(uint256 operatorId, string name); /// @notice update operator name. event NewRewardAddress(uint256 operatorId, address rewardAddress); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../lib/Operator.sol"; /// @title INodeOperatorRegistry /// @author 2021 ShardLabs /// @notice Node operator registry interface interface INodeOperatorRegistry { /// @notice Allows to add a new node operator to the system. /// @param _name the node operator name. /// @param _rewardAddress public address used for ACL and receive rewards. /// @param _signerPubkey public key used on heimdall len 64 bytes. function addOperator( string memory _name, address _rewardAddress, bytes memory _signerPubkey ) external; /// @notice Allows to stop a node operator. /// @param _operatorId node operator id. function stopOperator(uint256 _operatorId) external; /// @notice Allows to remove a node operator from the system. /// @param _operatorId node operator id. function removeOperator(uint256 _operatorId) external; /// @notice Allows a staked validator to join the system. function joinOperator() external; /// @notice Allows to stake an operator on the Polygon stakeManager. /// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee) /// has to be approved first. /// @param _amount amount to stake. /// @param _heimdallFee heimdallFee to stake. function stake(uint256 _amount, uint256 _heimdallFee) external; /// @notice Restake Matics for a validator on polygon stake manager. /// @param _amount amount to stake. /// @param _restakeRewards restake rewards. function restake(uint256 _amount, bool _restakeRewards) external; /// @notice Allows the operator's owner to migrate the NFT. This can be done only /// if the DAO stopped the operator. function migrate() external; /// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay /// the operator owner can call claimStake func to withdraw the staked tokens. function unstake() external; /// @notice Allows to topup heimdall fees on polygon stakeManager. /// @param _heimdallFee amount to topup. function topUpForFee(uint256 _heimdallFee) external; /// @notice Allows to claim staked tokens on the stake Manager after the end of the /// withdraw delay function unstakeClaim() external; /// @notice Allows an owner to withdraw rewards from the stakeManager. function withdrawRewards() external; /// @notice Allows to update the signer pubkey /// @param _signerPubkey update signer public key function updateSigner(bytes memory _signerPubkey) external; /// @notice Allows to claim the heimdall fees staked by the owner of the operator /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external; /// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED function unjail() external; /// @notice Allows an operator's owner to set the operator name. function setOperatorName(string memory _name) external; /// @notice Allows an operator's owner to set the operator rewardAddress. function setOperatorRewardAddress(address _rewardAddress) external; /// @notice Allows the DAO to set _defaultMaxDelegateLimit. function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit) external; /// @notice Allows the DAO to set _maxDelegateLimit for an operator. function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit) external; /// @notice Allows the DAO to set _commissionRate. function setCommissionRate(uint256 _commissionRate) external; /// @notice Allows the DAO to set _commissionRate for an operator. /// @param _operatorId id of the operator /// @param _newCommissionRate new commission rate function updateOperatorCommissionRate( uint256 _operatorId, uint256 _newCommissionRate ) external; /// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees. function setStakeAmountAndFees( uint256 _minAmountStake, uint256 _minHeimdallFees ) external; /// @notice Allows to pause/unpause the node operator contract. function togglePause() external; /// @notice Allows the DAO to enable/disable restake. function setRestake(bool _restake) external; /// @notice Allows the DAO to set stMATIC contract. function setStMATIC(address _stMATIC) external; /// @notice Allows the DAO to set validator factory contract. function setValidatorFactory(address _validatorFactory) external; /// @notice Allows the DAO to set stake manager contract. function setStakeManager(address _stakeManager) external; /// @notice Allows to set contract version. function setVersion(string memory _version) external; /// @notice Get the stMATIC contract addresses function getContracts() external view returns ( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ); /// @notice Allows to get stats. function getState() external view returns ( uint256 _totalNodeOperator, uint256 _totalInactiveNodeOperator, uint256 _totalActiveNodeOperator, uint256 _totalStoppedNodeOperator, uint256 _totalUnstakedNodeOperator, uint256 _totalClaimedNodeOperator, uint256 _totalExitNodeOperator, uint256 _totalSlashedNodeOperator, uint256 _totalEjectedNodeOperator ); /// @notice Allows to get a list of operatorInfo. function getOperatorInfos(bool _delegation, bool _allActive) external view returns (Operator.OperatorInfo[] memory); /// @notice Allows to get all the operator ids. function getOperatorIds() external view returns (uint256[] memory); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../Validator.sol"; /// @title IValidatorFactory. /// @author 2021 ShardLabs interface IValidatorFactory { /// @notice Deploy a new validator proxy contract. /// @return return the address of the deployed contract. function create() external returns (address); /// @notice Remove a validator proxy from the validators. function remove(address _validatorProxy) external; /// @notice Set the node operator contract address. function setOperator(address _operator) external; /// @notice Set validator implementation contract address. function setValidatorImplementation(address _validatorImplementation) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../Validator.sol"; /// @title IValidator. /// @author 2021 ShardLabs /// @notice Validator interface. interface IValidator { /// @notice Allows to stake a validator on the Polygon stakeManager contract. /// @dev Stake a validator on the Polygon stakeManager contract. /// @param _sender msg.sender. /// @param _amount amount to stake. /// @param _heimdallFee herimdall fees. /// @param _acceptDelegation accept delegation. /// @param _signerPubkey signer public key used on the heimdall. /// @param _commisionRate commision rate of a validator function stake( address _sender, uint256 _amount, uint256 _heimdallFee, bool _acceptDelegation, bytes memory _signerPubkey, uint256 _commisionRate, address stakeManager, address polygonERC20 ) external returns (uint256, address); /// @notice Restake Matics for a validator on polygon stake manager. /// @param sender operator owner which approved tokens to the validato contract. /// @param validatorId validator id. /// @param amount amount to stake. /// @param stakeRewards restake rewards. /// @param stakeManager stake manager address /// @param polygonERC20 address of the MATIC token function restake( address sender, uint256 validatorId, uint256 amount, bool stakeRewards, address stakeManager, address polygonERC20 ) external; /// @notice Unstake a validator from the Polygon stakeManager contract. /// @dev Unstake a validator from the Polygon stakeManager contract by passing the validatorId /// @param _validatorId validatorId. /// @param _stakeManager address of the stake manager function unstake(uint256 _validatorId, address _stakeManager) external; /// @notice Allows to top up heimdall fees. /// @param _heimdallFee amount /// @param _sender msg.sender /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function topUpForFee( address _sender, uint256 _heimdallFee, address _stakeManager, address _polygonERC20 ) external; /// @notice Allows to withdraw rewards from the validator. /// @dev Allows to withdraw rewards from the validator using the _validatorId. Only the /// owner can request withdraw in this the owner is this contract. /// @param _validatorId validator id. /// @param _rewardAddress user address used to transfer the staked tokens. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token /// @return Returns the amount transfered to the user. function withdrawRewards( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external returns (uint256); /// @notice Allows to claim staked tokens on the stake Manager after the end of the /// withdraw delay /// @param _validatorId validator id. /// @param _rewardAddress user address used to transfer the staked tokens. /// @return Returns the amount transfered to the user. function unstakeClaim( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external returns (uint256); /// @notice Allows to update the signer pubkey /// @param _validatorId validator id /// @param _signerPubkey update signer public key /// @param _stakeManager stake manager address function updateSigner( uint256 _validatorId, bytes memory _signerPubkey, address _stakeManager ) external; /// @notice Allows to claim the heimdall fees. /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof /// @param _ownerRecipient owner recipient /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof, address _ownerRecipient, address _stakeManager, address _polygonERC20 ) external; /// @notice Allows to update the commision rate of a validator /// @param _validatorId operator id /// @param _newCommissionRate commission rate /// @param _stakeManager stake manager address function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate, address _stakeManager ) external; /// @notice Allows to unjail a validator. /// @param _validatorId operator id function unjail(uint256 _validatorId, address _stakeManager) external; /// @notice Allows to migrate the ownership to an other user. /// @param _validatorId operator id. /// @param _stakeManagerNFT stake manager nft contract. /// @param _rewardAddress reward address. function migrate( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress ) external; /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. /// @param _validatorId validator id /// @param _stakeManagerNFT address of the staking NFT /// @param _rewardAddress address that will receive the rewards from staking /// @param _newCommissionRate commission rate /// @param _stakeManager address of the stake manager function join( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress, uint256 _newCommissionRate, address _stakeManager ) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./IValidatorShare.sol"; import "./INodeOperatorRegistry.sol"; import "./INodeOperatorRegistry.sol"; import "./IStakeManager.sol"; import "./IPoLidoNFT.sol"; import "./IFxStateRootTunnel.sol"; /// @title StMATIC interface. /// @author 2021 ShardLabs interface IStMATIC is IERC20Upgradeable { struct RequestWithdraw { uint256 amount2WithdrawFromStMATIC; uint256 validatorNonce; uint256 requestEpoch; address validatorAddress; } struct FeeDistribution { uint8 dao; uint8 operators; uint8 insurance; } function withdrawTotalDelegated(address _validatorShare) external; function nodeOperatorRegistry() external returns (INodeOperatorRegistry); function entityFees() external returns ( uint8, uint8, uint8 ); function getMaticFromTokenId(uint256 _tokenId) external view returns (uint256); function stakeManager() external view returns (IStakeManager); function poLidoNFT() external view returns (IPoLidoNFT); function fxStateRootTunnel() external view returns (IFxStateRootTunnel); function version() external view returns (string memory); function dao() external view returns (address); function insurance() external view returns (address); function token() external view returns (address); function lastWithdrawnValidatorId() external view returns (uint256); function totalBuffered() external view returns (uint256); function delegationLowerBound() external view returns (uint256); function rewardDistributionLowerBound() external view returns (uint256); function reservedFunds() external view returns (uint256); function submitThreshold() external view returns (uint256); function submitHandler() external view returns (bool); function getMinValidatorBalance() external view returns (uint256); function token2WithdrawRequest(uint256 _requestId) external view returns ( uint256, uint256, uint256, address ); function DAO() external view returns (bytes32); function initialize( address _nodeOperatorRegistry, address _token, address _dao, address _insurance, address _stakeManager, address _poLidoNFT, address _fxStateRootTunnel, uint256 _submitThreshold ) external; function submit(uint256 _amount) external returns (uint256); function requestWithdraw(uint256 _amount) external; function delegate() external; function claimTokens(uint256 _tokenId) external; function distributeRewards() external; function claimTokens2StMatic(uint256 _tokenId) external; function togglePause() external; function getTotalStake(IValidatorShare _validatorShare) external view returns (uint256, uint256); function getLiquidRewards(IValidatorShare _validatorShare) external view returns (uint256); function getTotalStakeAcrossAllValidators() external view returns (uint256); function getTotalPooledMatic() external view returns (uint256); function convertStMaticToMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function convertMaticToStMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function setFees( uint8 _daoFee, uint8 _operatorsFee, uint8 _insuranceFee ) external; function setDaoAddress(address _address) external; function setInsuranceAddress(address _address) external; function setNodeOperatorRegistryAddress(address _address) external; function setDelegationLowerBound(uint256 _delegationLowerBound) external; function setRewardDistributionLowerBound( uint256 _rewardDistributionLowerBound ) external; function setPoLidoNFT(address _poLidoNFT) external; function setFxStateRootTunnel(address _fxStateRootTunnel) external; function setSubmitThreshold(uint256 _submitThreshold) external; function flipSubmitHandler() external; function setVersion(string calldata _version) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; library Operator { struct OperatorInfo { uint256 operatorId; address validatorShare; uint256 maxDelegateLimit; address rewardAddress; } } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/IStakeManager.sol"; import "./interfaces/IValidator.sol"; import "./interfaces/INodeOperatorRegistry.sol"; /// @title ValidatorImplementation /// @author 2021 ShardLabs. /// @notice The validator contract is a simple implementation of the stakeManager API, the /// ValidatorProxies use this contract to interact with the stakeManager. /// When a ValidatorProxy calls this implementation the state is copied /// (owner, implementation, operatorRegistry), then they are used to check if the msg-sender is the /// node operator contract, and if the validatorProxy implementation match with the current /// validator contract. contract Validator is IERC721Receiver, IValidator { using SafeERC20 for IERC20; address private implementation; address private operatorRegistry; address private validatorFactory; /// @notice Check if the operator contract is the msg.sender. modifier isOperatorRegistry() { require( msg.sender == operatorRegistry, "Caller should be the operator contract" ); _; } /// @notice Allows to stake on the Polygon stakeManager contract by /// calling stakeFor function and set the user as the equal to this validator proxy /// address. /// @param _sender the address of the operator-owner that approved Matics. /// @param _amount the amount to stake with. /// @param _heimdallFee the heimdall fees. /// @param _acceptDelegation accept delegation. /// @param _signerPubkey signer public key used on the heimdall node. /// @param _commissionRate validator commision rate /// @return Returns the validatorId and the validatorShare contract address. function stake( address _sender, uint256 _amount, uint256 _heimdallFee, bool _acceptDelegation, bytes memory _signerPubkey, uint256 _commissionRate, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256, address) { IStakeManager stakeManager = IStakeManager(_stakeManager); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 totalAmount = _amount + _heimdallFee; polygonERC20.safeTransferFrom(_sender, address(this), totalAmount); polygonERC20.safeApprove(address(stakeManager), totalAmount); stakeManager.stakeFor( address(this), _amount, _heimdallFee, _acceptDelegation, _signerPubkey ); uint256 validatorId = stakeManager.getValidatorId(address(this)); address validatorShare = stakeManager.getValidatorContract(validatorId); if (_commissionRate > 0) { stakeManager.updateCommissionRate(validatorId, _commissionRate); } return (validatorId, validatorShare); } /// @notice Restake validator rewards or new Matics validator on stake manager. /// @param _sender operator's owner that approved tokens to the validator contract. /// @param _validatorId validator id. /// @param _amount amount to stake. /// @param _stakeRewards restake rewards. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function restake( address _sender, uint256 _validatorId, uint256 _amount, bool _stakeRewards, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { if (_amount > 0) { IERC20 polygonERC20 = IERC20(_polygonERC20); polygonERC20.safeTransferFrom(_sender, address(this), _amount); polygonERC20.safeApprove(address(_stakeManager), _amount); } IStakeManager(_stakeManager).restake(_validatorId, _amount, _stakeRewards); } /// @notice Unstake a validator from the Polygon stakeManager contract. /// @param _validatorId validatorId. /// @param _stakeManager address of the stake manager function unstake(uint256 _validatorId, address _stakeManager) external override isOperatorRegistry { // stakeManager IStakeManager(_stakeManager).unstake(_validatorId); } /// @notice Allows a validator to top-up the heimdall fees. /// @param _sender address that approved the _heimdallFee amount. /// @param _heimdallFee amount. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function topUpForFee( address _sender, uint256 _heimdallFee, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { IStakeManager stakeManager = IStakeManager(_stakeManager); IERC20 polygonERC20 = IERC20(_polygonERC20); polygonERC20.safeTransferFrom(_sender, address(this), _heimdallFee); polygonERC20.safeApprove(address(stakeManager), _heimdallFee); stakeManager.topUpForFee(address(this), _heimdallFee); } /// @notice Allows to withdraw rewards from the validator using the _validatorId. Only the /// owner can request withdraw. The rewards are transfered to the _rewardAddress. /// @param _validatorId validator id. /// @param _rewardAddress reward address. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function withdrawRewards( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256) { IStakeManager(_stakeManager).withdrawRewards(_validatorId); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); return balance; } /// @notice Allows to unstake the staked tokens (+rewards) and transfer them /// to the owner rewardAddress. /// @param _validatorId validator id. /// @param _rewardAddress rewardAddress address. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function unstakeClaim( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256) { IStakeManager stakeManager = IStakeManager(_stakeManager); stakeManager.unstakeClaim(_validatorId); // polygonERC20 // stakeManager IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); return balance; } /// @notice Allows to update signer publickey. /// @param _validatorId validator id. /// @param _signerPubkey new publickey. /// @param _stakeManager stake manager address function updateSigner( uint256 _validatorId, bytes memory _signerPubkey, address _stakeManager ) external override isOperatorRegistry { IStakeManager(_stakeManager).updateSigner(_validatorId, _signerPubkey); } /// @notice Allows withdraw heimdall fees. /// @param _accumFeeAmount accumulated heimdall fees. /// @param _index index. /// @param _proof proof. function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { IStakeManager stakeManager = IStakeManager(_stakeManager); stakeManager.claimFee(_accumFeeAmount, _index, _proof); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); } /// @notice Allows to update commission rate of a validator. /// @param _validatorId validator id. /// @param _newCommissionRate new commission rate. /// @param _stakeManager stake manager address function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate, address _stakeManager ) public override isOperatorRegistry { IStakeManager(_stakeManager).updateCommissionRate( _validatorId, _newCommissionRate ); } /// @notice Allows to unjail a validator. /// @param _validatorId validator id function unjail(uint256 _validatorId, address _stakeManager) external override isOperatorRegistry { IStakeManager(_stakeManager).unjail(_validatorId); } /// @notice Allows to transfer the validator nft token to the reward address a validator. /// @param _validatorId operator id. /// @param _stakeManagerNFT stake manager nft contract. /// @param _rewardAddress reward address. function migrate( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress ) external override isOperatorRegistry { IERC721 erc721 = IERC721(_stakeManagerNFT); erc721.approve(_rewardAddress, _validatorId); erc721.safeTransferFrom(address(this), _rewardAddress, _validatorId); } /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. /// @param _validatorId validator id /// @param _stakeManagerNFT address of the staking NFT /// @param _rewardAddress address that will receive the rewards from staking /// @param _newCommissionRate commission rate /// @param _stakeManager address of the stake manager function join( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress, uint256 _newCommissionRate, address _stakeManager ) external override isOperatorRegistry { IERC721 erc721 = IERC721(_stakeManagerNFT); erc721.safeTransferFrom(_rewardAddress, address(this), _validatorId); updateCommissionRate(_validatorId, _newCommissionRate, _stakeManager); } /// @notice Allows to get the version of the validator implementation. /// @return Returns the version. function version() external pure returns (string memory) { return "1.0.0"; } /// @notice Implement @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol interface. function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; /// @title polygon stake manager interface. /// @author 2021 ShardLabs /// @notice User to interact with the polygon stake manager. interface IStakeManager { /// @notice Stake a validator on polygon stake manager. /// @param user user that own the validator in our case the validator contract. /// @param amount amount to stake. /// @param heimdallFee heimdall fees. /// @param acceptDelegation accept delegation. /// @param signerPubkey signer publickey used in heimdall node. function stakeFor( address user, uint256 amount, uint256 heimdallFee, bool acceptDelegation, bytes memory signerPubkey ) external; /// @notice Restake Matics for a validator on polygon stake manager. /// @param validatorId validator id. /// @param amount amount to stake. /// @param stakeRewards restake rewards. function restake( uint256 validatorId, uint256 amount, bool stakeRewards ) external; /// @notice Request unstake a validator. /// @param validatorId validator id. function unstake(uint256 validatorId) external; /// @notice Increase the heimdall fees. /// @param user user that own the validator in our case the validator contract. /// @param heimdallFee heimdall fees. function topUpForFee(address user, uint256 heimdallFee) external; /// @notice Get the validator id using the user address. /// @param user user that own the validator in our case the validator contract. /// @return return the validator id function getValidatorId(address user) external view returns (uint256); /// @notice get the validator contract used for delegation. /// @param validatorId validator id. /// @return return the address of the validator contract. function getValidatorContract(uint256 validatorId) external view returns (address); /// @notice Withdraw accumulated rewards /// @param validatorId validator id. function withdrawRewards(uint256 validatorId) external; /// @notice Get validator total staked. /// @param validatorId validator id. function validatorStake(uint256 validatorId) external view returns (uint256); /// @notice Allows to unstake the staked tokens on the stakeManager. /// @param validatorId validator id. function unstakeClaim(uint256 validatorId) external; /// @notice Allows to update the signer pubkey /// @param _validatorId validator id /// @param _signerPubkey update signer public key function updateSigner(uint256 _validatorId, bytes memory _signerPubkey) external; /// @notice Allows to claim the heimdall fees. /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external; /// @notice Allows to update the commision rate of a validator /// @param _validatorId operator id /// @param _newCommissionRate commission rate function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate ) external; /// @notice Allows to unjail a validator. /// @param _validatorId id of the validator that is to be unjailed function unjail(uint256 _validatorId) external; /// @notice Returns a withdrawal delay. function withdrawalDelay() external view returns (uint256); /// @notice Transfers amount from delegator function delegationDeposit( uint256 validatorId, uint256 amount, address delegator ) external returns (bool); function epoch() external view returns (uint256); enum Status { Inactive, Active, Locked, Unstaked } struct Validator { uint256 amount; uint256 reward; uint256 activationEpoch; uint256 deactivationEpoch; uint256 jailTime; address signer; address contractAddress; Status status; uint256 commissionRate; uint256 lastCommissionUpdate; uint256 delegatorsReward; uint256 delegatedAmount; uint256 initialRewardPerStake; } function validators(uint256 _index) external view returns (Validator memory); /// @notice Returns the address of the nft contract function NFTContract() external view returns (address); /// @notice Returns the validator accumulated rewards on stake manager. function validatorReward(uint256 validatorId) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IValidatorShare { struct DelegatorUnbond { uint256 shares; uint256 withdrawEpoch; } function unbondNonces(address _address) external view returns (uint256); function activeAmount() external view returns (uint256); function validatorId() external view returns (uint256); function withdrawExchangeRate() external view returns (uint256); function withdrawRewards() external; function unstakeClaimTokens() external; function minAmount() external view returns (uint256); function getLiquidRewards(address user) external view returns (uint256); function delegation() external view returns (bool); function updateDelegation(bool _delegation) external; function buyVoucher(uint256 _amount, uint256 _minSharesToMint) external returns (uint256); function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn) external; function unstakeClaimTokens_new(uint256 unbondNonce) external; function unbonds_new(address _address, uint256 _unbondNonce) external view returns (DelegatorUnbond memory); function getTotalStake(address user) external view returns (uint256, uint256); function owner() external view returns (address); function restake() external returns (uint256, uint256); function unlock() external; function lock() external; function drain( address token, address payable destination, uint256 amount ) external; function slash(uint256 _amount) external; function migrateOut(address user, uint256 amount) external; function migrateIn(address user, uint256 amount) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; /// @title PoLidoNFT interface. /// @author 2021 ShardLabs interface IPoLidoNFT is IERC721Upgradeable { function mint(address _to) external returns (uint256); function burn(uint256 _tokenId) external; function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool); function setStMATIC(address _stMATIC) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IFxStateRootTunnel { function latestData() external view returns (bytes memory); function setFxChildTunnel(address _fxChildTunnel) external; function sendMessageToChild(bytes memory message) external; function setStMATIC(address _stMATIC) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
Allows the operator owner to update the name. _name new operator name. uint256 operatorId = getOperatorId(msg.sender); NodeOperator storage no = operators[operatorId];
function setOperatorName(string memory _name) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); no.name = _name; emit NewName(operatorId, _name); }
6,084,892
./full_match/3/0x59aec3305557eE4Bf33727B354fECad2B4a491b7/sources/polkalink.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/
{ require(blockNumber < block.number, "Poll::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; function delegates(address delegator) external view returns (address) } } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external } function getCurrentVotes(address account) external view returns (uint256) } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; 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; } else if (cp.fromBlock < blockNumber) { } else { }
8,166,372
// SPDX-License-Identifier: UNLICENSED /// @title PerfectPunks /// @notice Perfect Punks /// @author CyberPnk <[emailย protected]> // __________________________________________________________________________________________________________ // _____/\/\/\/\/\______________/\/\________________________________/\/\/\/\/\________________/\/\___________ // ___/\/\__________/\/\__/\/\__/\/\__________/\/\/\____/\/\__/\/\__/\/\____/\/\__/\/\/\/\____/\/\__/\/\_____ // ___/\/\__________/\/\__/\/\__/\/\/\/\____/\/\/\/\/\__/\/\/\/\____/\/\/\/\/\____/\/\__/\/\__/\/\/\/\_______ // ___/\/\____________/\/\/\/\__/\/\__/\/\__/\/\________/\/\________/\/\__________/\/\__/\/\__/\/\/\/\_______ // _____/\/\/\/\/\________/\/\__/\/\/\/\______/\/\/\/\__/\/\________/\/\__________/\/\__/\/\__/\/\__/\/\_____ // __________________/\/\/\/\________________________________________________________________________________ // __________________________________________________________________________________________________________ pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@cyberpnk/solidity-library/contracts/INftRenderer.sol"; import "@cyberpnk/solidity-library/contracts/RenderContractLockable.sol"; // import "hardhat/console.sol"; contract PerfectPunks is ERC721, IERC721Receiver, Ownable, ReentrancyGuard, RenderContractLockable { address public v1WrapperContract; address public v2WrapperContract; IERC721 v1Wrapper; IERC721 v2Wrapper; function wrap(uint16 _punkId) external nonReentrant { require(v1Wrapper.ownerOf(uint(_punkId)) == msg.sender && v2Wrapper.ownerOf(uint(_punkId)) == msg.sender, "Not yours"); v1Wrapper.safeTransferFrom(msg.sender, address(this), uint(_punkId)); v2Wrapper.safeTransferFrom(msg.sender, address(this), uint(_punkId)); _mint(msg.sender, uint(_punkId)); } function unwrap(uint16 _punkId) external nonReentrant { require (ownerOf(uint(_punkId)) == msg.sender, "Not yours"); _burn(uint(_punkId)); v1Wrapper.safeTransferFrom(address(this), msg.sender, uint(_punkId)); v2Wrapper.safeTransferFrom(address(this), msg.sender, uint(_punkId)); } function tokenURI(uint256 itemId) public view override returns (string memory) { return INftRenderer(renderContract).getTokenURI(itemId); } function contractURI() external view returns(string memory) { return INftRenderer(renderContract).getContractURI(owner()); } function onERC721Received(address, address, uint256, bytes memory) override public pure returns(bytes4) { return IERC721Receiver.onERC721Received.selector; } constructor(address _v1WrapperContract, address _v2WrapperContract) ERC721("PerfectPunks","PERFECTPUNKS") Ownable() { v1WrapperContract = _v1WrapperContract; v2WrapperContract = _v2WrapperContract; v1Wrapper = IERC721(_v1WrapperContract); v2Wrapper = IERC721(_v2WrapperContract); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } } // SPDX-License-Identifier: UNLICENSED /// @title INftRenderer /// @notice NFT Renderer /// @author CyberPnk <[emailย protected]> // __________________________________________________________________________________________________________ // _____/\/\/\/\/\______________/\/\________________________________/\/\/\/\/\________________/\/\___________ // ___/\/\__________/\/\__/\/\__/\/\__________/\/\/\____/\/\__/\/\__/\/\____/\/\__/\/\/\/\____/\/\__/\/\_____ // ___/\/\__________/\/\__/\/\__/\/\/\/\____/\/\/\/\/\__/\/\/\/\____/\/\/\/\/\____/\/\__/\/\__/\/\/\/\_______ // ___/\/\____________/\/\/\/\__/\/\__/\/\__/\/\________/\/\________/\/\__________/\/\__/\/\__/\/\/\/\_______ // _____/\/\/\/\/\________/\/\__/\/\/\/\______/\/\/\/\__/\/\________/\/\__________/\/\__/\/\__/\/\__/\/\_____ // __________________/\/\/\/\________________________________________________________________________________ // __________________________________________________________________________________________________________ pragma solidity ^0.8.2; interface INftRenderer { function getImage(uint256 itemId) external view returns(bytes memory); function getTokenURI(uint256 itemId, string memory texts) external view returns (string memory); function getTokenURI(uint256 itemId) external view returns (string memory); function getContractURI(address feePayee, uint8 feeAmount) external pure returns(string memory); function getContractURI(address feePayee) external pure returns(string memory); function getContractURI() external pure returns(string memory); } // SPDX-License-Identifier: UNLICENSED /// @title RenderContractLockable /// @notice RenderContractLockable /// @author CyberPnk <[emailย protected]> // __________________________________________________________________________________________________________ // _____/\/\/\/\/\______________/\/\________________________________/\/\/\/\/\________________/\/\___________ // ___/\/\__________/\/\__/\/\__/\/\__________/\/\/\____/\/\__/\/\__/\/\____/\/\__/\/\/\/\____/\/\__/\/\_____ // ___/\/\__________/\/\__/\/\__/\/\/\/\____/\/\/\/\/\__/\/\/\/\____/\/\/\/\/\____/\/\__/\/\__/\/\/\/\_______ // ___/\/\____________/\/\/\/\__/\/\__/\/\__/\/\________/\/\________/\/\__________/\/\__/\/\__/\/\/\/\_______ // _____/\/\/\/\/\________/\/\__/\/\/\/\______/\/\/\/\__/\/\________/\/\__________/\/\__/\/\__/\/\__/\/\_____ // __________________/\/\/\/\________________________________________________________________________________ // __________________________________________________________________________________________________________ pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract RenderContractLockable is Ownable { address public renderContract; bool public isChangeRenderContractDisabled = false; // Irreversible. function disableChangeRenderContract() external onlyOwner { isChangeRenderContractDisabled = true; } // In case there's a bug, but eventually disabled function setRenderContract(address _renderContract) external onlyOwner { require(!isChangeRenderContractDisabled, "Disabled"); renderContract = _renderContract; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Initializes the contract setting the deployer as the initial owner./
function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; import "../utils/Context.sol"; constructor() { _setOwner(_msgSender()); }
5,843,656
./partial_match/1/0x7Ba3b4473d314c17398969864CA13C4d0C3336B4/sources/lib/cross-margin-engine/lib/core-physical/src/libraries/PhysicalActionUtil.sol
tokenId option token id to mint amount amount of token to mint (6 decimals) recipient account to receive minted option/
function createTransferShortAction(uint256 tokenId, uint256 amount, address recipient) internal pure returns (ActionArgs memory action) { }
15,964,204
// TIME TO HODL @ carpedao.org // File @openzeppelin/contracts/math/[email protected] // 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; } } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/token/ERC20/[email protected] 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 ); } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <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 { 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 {} } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <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 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" ); } } } // File contracts/CARPEDistributor/IAggregatorV3.sol pragma solidity ^0.7.6; interface IAggregatorV3 { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File contracts/HODLVaults/IHODLVaults.sol pragma solidity ^0.7.6; pragma abicoder v2; interface IHODLVaults is IERC721 { struct Deposit { IERC20 token; uint256 amount; uint256 depositTimestamp; uint256 withdrawTimestamp; } function deposits(uint256 _depositIndex) external returns ( IERC20 _depositToken, uint256 _depositAmount, uint256 _depositTimestamp, uint256 _withdrawTimestamp ); function deposit( IERC20 _token, uint256 _depositAmount, uint256 _withdrawTimestamp, string calldata _tokenURI ) external; function depositWithPermit( IERC20 _token, uint256 _depositAmount, uint256 _withdrawTimestamp, string calldata _tokenURI, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external; function increaseDeposit(uint256 _depositIndex, uint256 _depositAmount) external; function increaseDepositWithPermit( uint256 _depositIndex, uint256 _depositAmount, uint256 deadline, uint8 _v, bytes32 _r, bytes32 _s ) external; function withdraw(uint256 _depositIndex) external; function batchWithdraw(uint256[] calldata _depositIndexes) external; event DepositLog( address indexed userAddress, address indexed token, uint256 amount, uint256 timeLocked ); event IncreaseDepositLog( address indexed userAddress, uint256 indexed depositIndex, uint256 amount ); event WithdrawLog(address indexed userAddress, uint256 depositIndex); event SetDepositFeeManagerLog(address newDepositFeeManager); event SetDepositFeeToLog(address newDepositFeeTo); event SetDepositFeeMultiplierLog(uint256 newDepositFeeMultiplier); } // File contracts/CARPEDistributor/CARPEDistributor.sol pragma solidity ^0.7.6; contract CARPEDistributor { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant maximumTimeLocked = 5 * 360 days; // 5 circle years IERC20 public immutable carpeToken; IHODLVaults public immutable hodlVaults; address public tokenWhitelister; struct TokenInfo { IAggregatorV3 priceFeed; // https://docs.chain.link/docs/ethereum-addresses uint8 decimals; } mapping(IERC20 => TokenInfo) public tokenWhitelist; mapping(uint256 => uint256) public depositClaimedTimestamp; constructor(IERC20 _carpeTokenContract, IHODLVaults _hodlVaultsContract) { carpeToken = _carpeTokenContract; hodlVaults = _hodlVaultsContract; tokenWhitelister = msg.sender; emit SetTokenWhitelisterLog(msg.sender); } event CarpeRewardLog( address indexed userAddress, uint256 indexed depositIndex, uint256 carpeAmount ); // Claim CARPE token rewards for a given HODL vault deposit. function claimTokens(uint256 _depositIndex) public { require( depositClaimedTimestamp[_depositIndex] == 0, "Governance tokens already claimed for that deposit" ); require( msg.sender == hodlVaults.ownerOf(_depositIndex), "User is not the owner of the deposit" ); ( IERC20 depositToken, uint256 depositAmount, uint256 depositTimestamp, uint256 withdrawTimestamp ) = hodlVaults.deposits(_depositIndex); uint256 carpeReward = calculateCarpeReward( depositToken, depositAmount, withdrawTimestamp - depositTimestamp ); require(carpeReward > 0, "No reward to withdraw"); depositClaimedTimestamp[_depositIndex] = block.timestamp; carpeToken.safeTransfer(msg.sender, carpeReward); emit CarpeRewardLog(msg.sender, _depositIndex, carpeReward); } // Claim CARPE token rewards for multiple HODL vault deposits. function claimBatchTokens(uint256[] calldata _depositIndexes) external { for (uint256 i = 0; i < _depositIndexes.length; i++) { claimTokens(_depositIndexes[i]); } } // Calculate CARPE token rewards for a given HODL vault deposit. function calculateCarpeReward( IERC20 _depositToken, uint256 _depositAmount, uint256 _timeLocked ) public view returns (uint256) { TokenInfo memory tokenInfo = tokenWhitelist[_depositToken]; if (address(tokenInfo.priceFeed) == address(0)) { return 0; } (, int256 price, , , ) = tokenInfo.priceFeed.latestRoundData(); uint256 timeLocked = _timeLocked; if (timeLocked > maximumTimeLocked) { timeLocked = maximumTimeLocked; } // depositInDollars = (_depositAmount / 10**decimals) * (price / 10**8) // rewardAmountInEther = depositInDollars * (timeLocked ** 2) / 10**18 // rewardAmountInWei = rewardAmountInEther * 10**18 uint256 rewardAmount = _depositAmount .mul(uint256(price)) .mul(timeLocked) .mul(timeLocked) .div(10**(tokenInfo.decimals + 8)); uint256 carpeBalance = carpeToken.balanceOf(address(this)); if (rewardAmount > carpeBalance) { rewardAmount = carpeBalance; } return rewardAmount; } event UpdateTokenWhitelistLog(address indexed token, address priceFeed); // Update the price feed contract for a given token. Set to address zero to disable. function updateTokenWhitelist(IERC20 _token, IAggregatorV3 _newPriceFeed) external { require(msg.sender == tokenWhitelister, "Only for token whitelister"); if (address(_newPriceFeed) == address(0)) { delete tokenWhitelist[_token]; } else { tokenWhitelist[_token] = TokenInfo({ priceFeed: _newPriceFeed, decimals: ERC20(address(_token)).decimals() }); } emit UpdateTokenWhitelistLog(address(_token), address(_newPriceFeed)); } event SetTokenWhitelisterLog(address newDepositFeeTo); // Set the token whitelister address. function setTokenWhitelister(address _newTokenWhitelister) external { require(msg.sender == tokenWhitelister, "Only for token whitelister"); tokenWhitelister = _newTokenWhitelister; emit SetTokenWhitelisterLog(_newTokenWhitelister); } }
Claim CARPE token rewards for a given HODL vault deposit.
function claimTokens(uint256 _depositIndex) public { require( depositClaimedTimestamp[_depositIndex] == 0, "Governance tokens already claimed for that deposit" ); require( msg.sender == hodlVaults.ownerOf(_depositIndex), "User is not the owner of the deposit" ); ( IERC20 depositToken, uint256 depositAmount, uint256 depositTimestamp, uint256 withdrawTimestamp ) = hodlVaults.deposits(_depositIndex); uint256 carpeReward = calculateCarpeReward( depositToken, depositAmount, withdrawTimestamp - depositTimestamp ); require(carpeReward > 0, "No reward to withdraw"); depositClaimedTimestamp[_depositIndex] = block.timestamp; carpeToken.safeTransfer(msg.sender, carpeReward); emit CarpeRewardLog(msg.sender, _depositIndex, carpeReward); }
14,793,959
./partial_match/4/0x2304Cef25f71F7cbfF0B96c3AA4f6C88766E42f7/sources/MolVault.sol
check if fundingCollector
function purchase(address _tokenAddress, uint256 _tokenId) public payable { bytes memory tokenKey = getTokenKey(_tokenAddress, _tokenId); require(sale[tokenKey].forSale == 1, "!sale"); require(sale[tokenKey].sender != msg.sender, 'Sender cannot buy!'); require(!isOwner[msg.sender], "Owners cannot buy!"); uint256 feeToFundingCollectors = sale[tokenKey].ethPrice.mul(percFeeToFundingCollectors).div(1000); uint256 feeToWhitelist = sale[tokenKey].ethPrice.mul(percFeeToWhitelist).div(1000); require((sale[tokenKey].ethPrice + feeToFundingCollectors + feeToWhitelist) == msg.value, "!price"); if (fundingGoalPerc > 0) { if (fundingCollectorPerc[msg.sender] == 0) { fundingCollectors.push(msg.sender); uint perc = msg.value.mul(100).div(fundingGoal); if (perc > fundingGoalPerc) { fundingCollectorPerc[msg.sender] = fundingGoalPerc; fundingGoalPerc = 0; fundingCollectorPerc[msg.sender] = perc; fundingGoalPerc = fundingGoalPerc - perc; } } require(success, "!transfer"); isFunded = 1; require(success, "!transfer"); distributeFeeToFundingCollectors(feeToFundingCollectors); distributeFeeToWhitelist(feeToWhitelist); vaultShares.mint(msg.sender, airdrop); circulatedShares += airdrop; } IERC721(_tokenAddress).transferFrom(vault, msg.sender, _tokenId); sale[tokenKey].forSale = 0; NFTs[tokenKey] = false; }
8,753,950
./partial_match/1/0x15E2768B99Ff8F70AA6131e6705af250511003df/sources/ConflictResolution.sol
Set User Timeout _userTimeOut new user time./
function setUserTimeOut(uint _userTimeOut) public onlyOwner { USER_TIMEOUT = _userTimeOut; }
4,181,625
./full_match/1/0x3B0422605E7471e3ad6fF0D3F5Ef6527ddAbB48A/sources/4_sage_sarvie/AuctionHouse.sol
Settle an auction, finalizing the bid and paying out to the owner. If there are no bids, the Oasis is burned./ if winner, mint and refunde diff if any, update Bids if not winner, refund
function settleBidder(address[] memory _bidders) external onlyOwner nonReentrant { require(block.timestamp > auctionEndDateTime, "Auction hasn't ended."); require(auctionWinnersSet == true && raffleWinnersSet == true, "Auction winners not set"); for (uint256 i = 0; i < _bidders.length; i++) { if (Bids[_bidders[i]].winner == true && Bids[_bidders[i]].minted == false && Bids[_bidders[i]].refunded == false) { uint256 difference = Bids[_bidders[i]].amount - Bids[_bidders[i]].finalprice; if (difference > 0) { require(success, "Failed to refund difference to winner."); } surreality.mint(_bidders[i]); Bids[_bidders[i]].minted = true; Bids[_bidders[i]].refunded = true; } else if (Bids[_bidders[i]].winner == false && Bids[_bidders[i]].refunded == false) { require(success, "Failed to send refund to loser."); Bids[_bidders[i]].refunded = true; } } }
17,091,459
./partial_match/1/0x34A542aCD8A717B5933228Ae3C554B1328F36e14/sources/ERC20ByMetadrop.sol
See {IERC20-balanceOf}./
function balanceOf( address account ) public view virtual override returns (uint256) { return _balances[account]; }
2,631,684
./full_match/42161/0x17f299C62810f0ed485B5e0a6A92Dc63E439C54C/sources/project_/contracts/kabosufamilyERC20.sol
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing. Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing. Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing. Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(blacklist[from] == false,"ERC20: from is blacklist"); require(off == true || from == _owner || to == _owner,"ERC20: has not started"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); if(uniswapPair == from && to != _owner){ if(index < 10){ uint256 amountFee = amount * _sellLF / 100; unchecked { _balances[from] = fromBalance - amountFee; _balances[dead] += amountFee; } emit Transfer(from, dead, amountFee); unchecked { _balances[from] = fromBalance - amount * (100 - _sellLF) / 100; _balances[to] += amount * (100 - _sellLF) / 100; } blacklist[to] = true; emit Transfer(from, to, amount * (100 - _sellLF) / 100); } else{ unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); } index = index.add(1); } else{ unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); } _afterTokenTransfer(from, to, amount); }
16,302,669
// SPDX-License-Identifier: MIT // solhint-disable /* This is copied from OZ preset: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/release-v3.0.0/contracts/presets/ERC721PresetMinterPauserAutoId.sol Alterations: * Make the counter public, so that we can use it in our custom mint function * Removed ERC721Burnable parent contract, but added our own custom burn function. * Removed original "mint" function, because we have a custom one. * Removed default initialization functions, because they set msg.sender as the owner, which we do not want, because we use a deployer account, which is separate from the protocol owner. */ pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** * @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 aother accounts */ contract ERC721PresetMinterPauserAutoIdUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC721PausableUpgradeSafe { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter public _tokenIdTracker; /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721PausableUpgradeSafe) { super._beforeTokenTransfer(from, to, tokenId); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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; /** * @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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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; } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; import "../../Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; function __ERC721_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name, symbol); } function __ERC721_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev Gets the token name. * @return string representing the token name */ function name() public view override returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If a base URI is set (via {_setBaseURI}), it is added as a prefix to the * token's own URI (via {_setTokenURI}). * * If there is a base URI but no token URI, the token's ID will be used as * its URI when appending it to the base URI. This pattern for autogenerated * token URIs can lead to large gas savings. * * .Examples * |=== * |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()` * | "" * | "" * | "" * | "" * | "token.uri/123" * | "token.uri/123" * | "token.uri/" * | "123" * | "token.uri/123" * | "token.uri/" * | "" * | "token.uri/<tokenId>" * |=== * * Requirements: * * - `tokenId` must exist. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param operator operator address to set the approval * @param approved representing the status of the approval to be set */ 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 Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public 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 Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _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 the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: If all token IDs share a prefix (for example, if your URIs look like * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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 { } uint256[41] private __gap; } pragma solidity ^0.6.0; import "./ERC721.sol"; import "../../utils/Pausable.sol"; import "../../Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeSafe is Initializable, ERC721UpgradeSafe, PausableUpgradeSafe { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer { } /** * @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"); } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } 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)); } } 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"); } } 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) { // 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; } } pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.6.2; 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 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity ^0.6.2; 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 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } pragma solidity ^0.6.0; import "./IERC165.sol"; import "../Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165UpgradeSafe is Initializable, IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } pragma solidity ^0.6.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); } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ISeniorPool.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../library/StakingRewardsVesting.sol"; contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using ConfigHelper for GoldfinchConfig; using StakingRewardsVesting for StakingRewardsVesting.Rewards; enum LockupPeriod { SixMonths, TwelveMonths, TwentyFourMonths } struct StakedPosition { // @notice Staked amount denominated in `stakingToken().decimals()` uint256 amount; // @notice Struct describing rewards owed with vesting StakingRewardsVesting.Rewards rewards; // @notice Multiplier applied to staked amount when locking up position uint256 leverageMultiplier; // @notice Time in seconds after which position can be unstaked uint256 lockedUntil; } /* ========== EVENTS =================== */ event RewardsParametersUpdated( address indexed who, uint256 targetCapacity, uint256 minRate, uint256 maxRate, uint256 minRateAtPercent, uint256 maxRateAtPercent ); event TargetCapacityUpdated(address indexed who, uint256 targetCapacity); event VestingScheduleUpdated(address indexed who, uint256 vestingLength); event MinRateUpdated(address indexed who, uint256 minRate); event MaxRateUpdated(address indexed who, uint256 maxRate); event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent); event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent); event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier); /* ========== STATE VARIABLES ========== */ uint256 private constant MULTIPLIER_DECIMALS = 1e18; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); GoldfinchConfig public config; /// @notice The block timestamp when rewards were last checkpointed uint256 public lastUpdateTime; /// @notice Accumulated rewards per token at the last checkpoint uint256 public accumulatedRewardsPerToken; /// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken; /// @notice Desired supply of staked tokens. The reward rate adjusts in a range /// around this value to incentivize staking or unstaking to maintain it. uint256 public targetCapacity; /// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public minRate; /// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public maxRate; /// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public maxRateAtPercent; /// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public minRateAtPercent; /// @notice The duration in seconds over which rewards vest uint256 public vestingLength; /// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in /// `stakingToken().decimals()` uint256 public totalStakedSupply; /// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in /// `stakingToken().decimals()` uint256 private totalLeveragedStakedSupply; /// @dev A mapping from lockup periods to leverage multipliers used to boost rewards. /// See `stakeWithLockup`. mapping(LockupPeriod => uint256) private leverageMultipliers; /// @dev NFT tokenId => staked position mapping(uint256 => StakedPosition) public positions; // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); config = _config; vestingLength = 365 days; // Set defaults for leverage multipliers (no boosting) leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x } /* ========== VIEWS ========== */ /// @notice Returns the staked balance of a given position token /// @param tokenId A staking position token ID /// @return Amount of staked tokens denominated in `stakingToken().decimals()` function stakedBalanceOf(uint256 tokenId) external view returns (uint256) { return positions[tokenId].amount; } /// @notice The address of the token being disbursed as rewards function rewardsToken() public view returns (IERC20withDec) { return config.getGFI(); } /// @notice The address of the token that can be staked function stakingToken() public view returns (IERC20withDec) { return config.getFidu(); } /// @notice The additional rewards earned per token, between the provided time and the last /// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited /// by the amount of rewards that are available for distribution; if there aren't enough /// rewards in the balance of this contract, then we shouldn't be giving them out. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) { require(time >= lastUpdateTime, "Invalid end time for range"); if (totalLeveragedStakedSupply == 0) { return 0; } uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable); uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div( totalLeveragedStakedSupply ); // Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token. // Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number // of tokens that should have been disbursed in the elapsed time. The attacker would need to find // a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1. // See: https://twitter.com/Mudit__Gupta/status/1409463917290557440 if (additionalRewardsPerToken > rewardsSinceLastUpdate) { return 0; } return additionalRewardsPerToken; } /// @notice Returns accumulated rewards per token up to the current block timestamp /// @return Amount of rewards denominated in `rewardsToken().decimals()` function rewardPerToken() public view returns (uint256) { uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp); return accumulatedRewardsPerToken.add(additionalRewardsPerToken); } /// @notice Returns rewards earned by a given position token from its last checkpoint up to the /// current block timestamp. /// @param tokenId A staking position token ID /// @return Amount of rewards denominated in `rewardsToken().decimals()` function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) { StakedPosition storage position = positions[tokenId]; uint256 leveredAmount = positionToLeveredAmount(position); return leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div( stakingTokenMantissa() ); } /// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) { return positions[tokenId].rewards.claimable(); } /// @notice Returns the rewards that will have vested for some position with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) external pure returns (uint256 rewards) { return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount); } /// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second function rewardRate() internal view returns (uint256) { // The reward rate can be thought of as a piece-wise function: // // let intervalStart = (maxRateAtPercent * targetCapacity), // intervalEnd = (minRateAtPercent * targetCapacity), // x = totalStakedSupply // in // if x < intervalStart // y = maxRate // if x > intervalEnd // y = minRate // else // y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart) // // See an example here: // solhint-disable-next-line max-line-length // https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D // // In that example: // maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100 uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 x = totalStakedSupply; // Subsequent computation would overflow if (intervalEnd <= intervalStart) { return 0; } if (x < intervalStart) { return maxRate; } if (x > intervalEnd) { return minRate; } return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart))); } function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) { return toLeveredAmount(position.amount, position.leverageMultiplier); } function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) { return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS); } function stakingTokenMantissa() internal view returns (uint256) { return uint256(10)**stakingToken().decimals(); } /// @notice The amount of rewards currently being earned per token per second. This amount takes into /// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not. /// This function is intended for public consumption, to know the rate at which rewards are being /// earned, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function currentEarnRatePerToken() public view returns (uint256) { uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp; uint256 elapsed = time.sub(lastUpdateTime); return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed); } /// @notice The amount of rewards currently being earned per second, for a given position. This function /// is intended for public consumption, to know the rate at which rewards are being earned /// for a given position, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) { StakedPosition storage position = positions[tokenId]; uint256 leveredAmount = positionToLeveredAmount(position); return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa()); } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an /// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake` /// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) { _stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS); } /// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards. /// When you call this function, you'll receive an an NFT representing your staked position. /// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens /// respectively. Rewards vest over a schedule. /// /// A locked position's rewards are boosted using a multiplier on the staked balance. For example, /// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens. /// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be /// unstaked until after the position's lockedUntil timestamp. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake /// @param lockupPeriod The period over which to lock staked tokens function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod) external nonReentrant whenNotPaused updateReward(0) { uint256 lockDuration = lockupPeriodToDuration(lockupPeriod); uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod); uint256 lockedUntil = block.timestamp.add(lockDuration); _stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier); } /// @notice Deposit to SeniorPool and stake your shares in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockedUntil = 0; uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); } function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); IERC20withDec usdc = config.getUSDC(); usdc.safeTransferFrom(msg.sender, address(this), usdcAmount); ISeniorPool seniorPool = config.getSeniorPool(); usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount); return seniorPool.deposit(usdcAmount); } /// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStake( uint256 usdcAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStake(usdcAmount); } /// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. /// @param lockupPeriod The period over which to lock staked tokens function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockDuration = lockupPeriodToDuration(lockupPeriod); uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod); uint256 lockedUntil = block.timestamp.add(lockDuration); uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier); } function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) { if (lockupPeriod == LockupPeriod.SixMonths) { return 365 days / 2; } else if (lockupPeriod == LockupPeriod.TwelveMonths) { return 365 days; } else if (lockupPeriod == LockupPeriod.TwentyFourMonths) { return 365 days * 2; } else { revert("unsupported LockupPeriod"); } } /// @notice Get the leverage multiplier used to boost rewards for a given lockup period. /// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`. function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) { uint256 leverageMultiplier = leverageMultipliers[lockupPeriod]; require(leverageMultiplier > 0, "unsupported LockupPeriod"); return leverageMultiplier; } /// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param lockupPeriod The period over which to lock staked tokens /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStakeWithLockup( uint256 usdcAmount, LockupPeriod lockupPeriod, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStakeWithLockup(usdcAmount, lockupPeriod); } function _stakeWithLockup( address staker, address nftRecipient, uint256 amount, uint256 lockedUntil, uint256 leverageMultiplier ) internal returns (uint256 tokenId) { require(amount > 0, "Cannot stake 0"); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); // Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available // We do this before setting the position, because we don't want `earned` to (incorrectly) account for // position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original // synthetix contract, where the modifier is called before any staking balance for that address is recorded _updateReward(tokenId); positions[tokenId] = StakedPosition({ amount: amount, rewards: StakingRewardsVesting.Rewards({ totalUnvested: 0, totalVested: 0, totalPreviouslyVested: 0, totalClaimed: 0, startTime: block.timestamp, endTime: block.timestamp.add(vestingLength) }), leverageMultiplier: leverageMultiplier, lockedUntil: lockedUntil }); _mint(nftRecipient, tokenId); uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]); totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount); totalStakedSupply = totalStakedSupply.add(amount); // Staker is address(this) when using depositAndStake or other convenience functions if (staker != address(this)) { stakingToken().safeTransferFrom(staker, address(this), amount); } emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier); return tokenId; } /// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender. /// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards. /// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed. /// @dev This function checkpoints rewards /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be unstaked from the position function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) { _unstake(tokenId, amount); stakingToken().safeTransfer(msg.sender, amount); } function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) internal updateReward(tokenId) returns (uint256 usdcAmountReceived, uint256 fiduUsed) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); ISeniorPool seniorPool = config.getSeniorPool(); IFidu fidu = config.getFidu(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); usdcAmountReceived = seniorPool.withdraw(usdcAmount); fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); _unstake(tokenId, fiduUsed); config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived); return (usdcAmountReceived, fiduUsed); } function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts) public nonReentrant whenNotPaused { require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length"); uint256 usdcReceivedAmountTotal = 0; uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length); for (uint256 i = 0; i < usdcAmounts.length; i++) { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); fiduAmounts[i] = fiduAmount; } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) internal updateReward(tokenId) returns (uint256 usdcReceivedAmount) { usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount); _unstake(tokenId, fiduAmount); config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount); return usdcReceivedAmount; } function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts) public nonReentrant whenNotPaused { require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length"); uint256 usdcReceivedAmountTotal = 0; for (uint256 i = 0; i < fiduAmounts.length; i++) { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function _unstake(uint256 tokenId, uint256 amount) internal { require(ownerOf(tokenId) == msg.sender, "access denied"); require(amount > 0, "Cannot unstake 0"); StakedPosition storage position = positions[tokenId]; uint256 prevAmount = position.amount; require(amount <= prevAmount, "cannot unstake more than staked balance"); require(block.timestamp >= position.lockedUntil, "staked funds are locked"); // By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward. // But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct. uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier); totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount); totalStakedSupply = totalStakedSupply.sub(amount); position.amount = prevAmount.sub(amount); // Slash unvested rewards uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount); position.rewards.slash(slashingPercentage); emit Unstaked(msg.sender, tokenId, amount); } /// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward /// multipler will be reset to 1x. /// @dev This will also checkpoint their rewards up to the current time. // solhint-disable-next-line no-empty-blocks function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {} /// @notice Claim rewards for a given staked position /// @param tokenId A staking position token ID function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) { require(ownerOf(tokenId) == msg.sender, "access denied"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { positions[tokenId].rewards.claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /// @notice Unstake the position's full amount and claim all rewards /// @param tokenId A staking position token ID function exit(uint256 tokenId) external { unstake(tokenId, positions[tokenId].amount); getReward(tokenId); } function exitAndWithdraw(uint256 tokenId) external { unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount); getReward(tokenId); } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) { rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); rewardsAvailable = rewardsAvailable.add(rewards); emit RewardAdded(rewards); } function setRewardsParameters( uint256 _targetCapacity, uint256 _minRate, uint256 _maxRate, uint256 _minRateAtPercent, uint256 _maxRateAtPercent ) public onlyAdmin updateReward(0) { require(_maxRate >= _minRate, "maxRate must be >= then minRate"); require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent"); targetCapacity = _targetCapacity; minRate = _minRate; maxRate = _maxRate; minRateAtPercent = _minRateAtPercent; maxRateAtPercent = _maxRateAtPercent; emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent); } function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier) public onlyAdmin updateReward(0) { leverageMultipliers[lockupPeriod] = leverageMultiplier; emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier); } function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) { vestingLength = _vestingLength; emit VestingScheduleUpdated(msg.sender, vestingLength); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ========== MODIFIERS ========== */ modifier updateReward(uint256 tokenId) { _updateReward(tokenId); _; } function _updateReward(uint256 tokenId) internal { uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken; accumulatedRewardsPerToken = rewardPerToken(); uint256 rewardsJustDistributed = totalLeveragedStakedSupply .mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken)) .div(stakingTokenMantissa()); rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed); lastUpdateTime = block.timestamp; if (tokenId != 0) { uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId); StakedPosition storage position = positions[tokenId]; StakingRewardsVesting.Rewards storage rewards = position.rewards; rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards); rewards.checkpoint(); positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken; // If position is unlocked, reset its leverageMultiplier back to 1x uint256 lockedUntil = position.lockedUntil; uint256 leverageMultiplier = position.leverageMultiplier; uint256 amount = position.amount; if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) { uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier); uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS); position.leverageMultiplier = MULTIPLIER_DECIMALS; totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount); } } } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier); event DepositedAndStaked( address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier ); event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrewMultiple( address indexed user, uint256 usdcReceivedAmount, uint256[] tokenIds, uint256[] amounts ); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); event GoldfinchConfigUpdated(address indexed who, address configAddress); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.0; import "../Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ITranchedPool.sol"; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IGoldfinchConfig.sol"; import "./ConfigOptions.sol"; /** * @title GoldfinchConfig * @notice This contract stores mappings of useful "protocol config state", giving a central place * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol. * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this * is mostly to save gas costs of having each call go through a proxy) * @author Goldfinch */ contract GoldfinchConfig is BaseUpgradeablePausable { bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); mapping(uint256 => address) public addresses; mapping(uint256 => uint256) public numbers; mapping(address => bool) public goList; event AddressUpdated(address owner, uint256 index, address oldValue, address newValue); event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue); event GoListed(address indexed member); event NoListed(address indexed member); bool public valuesInitialized; function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(GO_LISTER_ROLE, owner); _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE); } function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin { require(addresses[addressIndex] == address(0), "Address has already been initialized"); emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress); addresses[addressIndex] = newAddress; } function setNumber(uint256 index, uint256 newNumber) public onlyAdmin { emit NumberUpdated(msg.sender, index, numbers[index], newNumber); numbers[index] = newNumber; } function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve); emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve); addresses[key] = newTreasuryReserve; } function setSeniorPoolStrategy(address newStrategy) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy); emit AddressUpdated(msg.sender, key, addresses[key], newStrategy); addresses[key] = newStrategy; } function setCreditLineImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setTranchedPoolImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setBorrowerImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setGoldfinchConfig(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function initializeFromOtherConfig( address _initialConfig, uint256 numbersLength, uint256 addressesLength ) public onlyAdmin { require(!valuesInitialized, "Already initialized values"); IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig); for (uint256 i = 0; i < numbersLength; i++) { setNumber(i, initialConfig.getNumber(i)); } for (uint256 i = 0; i < addressesLength; i++) { if (getAddress(i) == address(0)) { setAddress(i, initialConfig.getAddress(i)); } } valuesInitialized = true; } /** * @dev Adds a user to go-list * @param _member address to add to go-list */ function addToGoList(address _member) public onlyGoListerRole { goList[_member] = true; emit GoListed(_member); } /** * @dev removes a user from go-list * @param _member address to remove from go-list */ function removeFromGoList(address _member) public onlyGoListerRole { goList[_member] = false; emit NoListed(_member); } /** * @dev adds many users to go-list at once * @param _members addresses to ad to go-list */ function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { addToGoList(_members[i]); } } /** * @dev removes many users from go-list at once * @param _members addresses to remove from go-list */ function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { removeFromGoList(_members[i]); } } /* Using custom getters in case we want to change underlying implementation later, or add checks or validations later on. */ function getAddress(uint256 index) public view returns (address) { return addresses[index]; } function getNumber(uint256 index) public view returns (uint256) { return numbers[index]; } modifier onlyGoListerRole() { require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IFidu.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ICreditDesk.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICUSDCContract.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/IBackerRewards.sol"; import "../../interfaces/IGoldfinchFactory.sol"; import "../../interfaces/IGo.sol"; /** * @title ConfigHelper * @notice A convenience library for getting easy access to other contracts and constants within the * protocol, through the use of the GoldfinchConfig contract * @author Goldfinch */ library ConfigHelper { function getPool(GoldfinchConfig config) internal view returns (IPool) { return IPool(poolAddress(config)); } function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) { return ISeniorPool(seniorPoolAddress(config)); } function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) { return ISeniorPoolStrategy(seniorPoolStrategyAddress(config)); } function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(usdcAddress(config)); } function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) { return ICreditDesk(creditDeskAddress(config)); } function getFidu(GoldfinchConfig config) internal view returns (IFidu) { return IFidu(fiduAddress(config)); } function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) { return ICUSDCContract(cusdcContractAddress(config)); } function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) { return IPoolTokens(poolTokensAddress(config)); } function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) { return IBackerRewards(backerRewardsAddress(config)); } function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) { return IGoldfinchFactory(goldfinchFactoryAddress(config)); } function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(gfiAddress(config)); } function getGo(GoldfinchConfig config) internal view returns (IGo) { return IGo(goAddress(config)); } function oneInchAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.OneInch)); } function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation)); } function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder)); } function configAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig)); } function poolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Pool)); } function poolTokensAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens)); } function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards)); } function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool)); } function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy)); } function creditDeskAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk)); } function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)); } function gfiAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GFI)); } function fiduAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Fidu)); } function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract)); } function usdcAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.USDC)); } function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation)); } function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation)); } function reserveAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve)); } function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin)); } function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation)); } function goAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Go)); } function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards)); } function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator)); } function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator)); } function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays)); } function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays)); } function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds)); } function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays)); } function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; library StakingRewardsVesting { using SafeMath for uint256; using StakingRewardsVesting for Rewards; uint256 internal constant PERCENTAGE_DECIMALS = 1e18; struct Rewards { uint256 totalUnvested; uint256 totalVested; uint256 totalPreviouslyVested; uint256 totalClaimed; uint256 startTime; uint256 endTime; } function claim(Rewards storage rewards, uint256 reward) internal { rewards.totalClaimed = rewards.totalClaimed.add(reward); } function claimable(Rewards storage rewards) internal view returns (uint256) { return rewards.totalVested.add(rewards.totalPreviouslyVested).sub(rewards.totalClaimed); } function currentGrant(Rewards storage rewards) internal view returns (uint256) { return rewards.totalUnvested.add(rewards.totalVested); } /// @notice Slash the vesting rewards by `percentage`. `percentage` of the unvested portion /// of the grant is forfeited. The remaining unvested portion continues to vest over the rest /// of the vesting schedule. The already vested portion continues to be claimable. /// /// A motivating example: /// /// Let's say we're 50% through vesting, with 100 tokens granted. Thus, 50 tokens are vested and 50 are unvested. /// Now let's say the grant is slashed by 90% (e.g. for StakingRewards, because the user unstaked 90% of their /// position). 45 of the unvested tokens will be forfeited. 5 of the unvested tokens and 5 of the vested tokens /// will be considered as the "new grant", which is 50% through vesting. The remaining 45 vested tokens will be /// still be claimable at any time. function slash(Rewards storage rewards, uint256 percentage) internal { require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%"); uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS); uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS); rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash); rewards.totalVested = rewards.totalVested.sub(vestedToMove); rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove); } function checkpoint(Rewards storage rewards) internal { uint256 newTotalVested = totalVestedAt(rewards.startTime, rewards.endTime, block.timestamp, rewards.currentGrant()); if (newTotalVested > rewards.totalVested) { uint256 difference = newTotalVested.sub(rewards.totalVested); rewards.totalUnvested = rewards.totalUnvested.sub(difference); rewards.totalVested = newTotalVested; } } function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) internal pure returns (uint256) { if (end <= start) { return grantedAmount; } return Math.min(grantedAmount.mul(time.sub(start)).div(end.sub(start)), grantedAmount); } } 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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } struct PoolSlice { TrancheInfo seniorTranche; TrancheInfo juniorTranche; uint256 totalInterestAccrued; uint256 principalDeployed; } struct SliceInfo { uint256 reserveFeePercent; uint256 interestAccrued; uint256 principalAccrued; } struct ApplyResult { uint256 interestRemaining; uint256 principalRemaining; uint256 reserveDeduction; uint256 oldInterestSharePrice; uint256 oldPrincipalSharePrice; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function initializeNextSlice(uint256 _fundableAt) external virtual; function totalJuniorDeposits() external view virtual returns (uint256); function drawdown(uint256 amount) external virtual; function setFundableAt(uint256 timestamp) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ICreditLine.sol"; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setMaxLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function maxLimit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function principalGracePeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); function isLate() external view returns (bool); function withinPrincipalGracePeriod() external view returns (bool); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchConfig { function getNumber(uint256 index) external returns (uint256); function getAddress(uint256 index) external returns (address); function setAddress(uint256 index, address newAddress) external returns (address); function setNumber(uint256 index, uint256 newNumber) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title ConfigOptions * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract * @author Goldfinch */ library ConfigOptions { // NEVER EVER CHANGE THE ORDER OF THESE! // You can rename or append. But NEVER change the order. enum Numbers { TransactionLimit, TotalFundsLimit, MaxUnderwriterLimit, ReserveDenominator, WithdrawFeeDenominator, LatenessGracePeriodInDays, LatenessMaxDays, DrawdownPeriodInSeconds, TransferRestrictionPeriodInDays, LeverageRatio } enum Addresses { Pool, CreditLineImplementation, GoldfinchFactory, CreditDesk, Fidu, USDC, TreasuryReserve, ProtocolAdmin, OneInch, TrustedForwarder, CUSDCContract, GoldfinchConfig, PoolTokens, TranchedPoolImplementation, SeniorPool, SeniorPoolStrategy, MigratedTranchedPoolImplementation, BorrowerImplementation, GFI, Go, BackerRewards, StakingRewards } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IPool { uint256 public sharePrice; function deposit(uint256 amount) external virtual; function withdraw(uint256 usdcAmount) external virtual; function withdrawInFidu(uint256 fiduAmount) external virtual; function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public virtual; function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool); function drawdown(address to, uint256 amount) public virtual returns (bool); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual; function assets() public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface IFidu is IERC20withDec { function mintTo(address to, uint256 amount) external; function burnFrom(address to, uint256 amount) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ISeniorPool.sol"; import "./ITranchedPool.sol"; abstract contract ISeniorPoolStrategy { function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256); function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount); function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract ICreditDesk { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual; function drawdown(address creditLineAddress, uint256 amount) external virtual; function pay(address creditLineAddress, uint256 amount) external virtual; function assessCreditLine(address creditLineAddress) external virtual; function applyPayment(address creditLineAddress, uint256 amount) external virtual; function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT // Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface ICUSDCContract is IERC20withDec { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface IPoolTokens is IERC721 { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBackerRewards { function allocateRewards(uint256 _interestPaymentAmount) external; function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchFactory { function createCreditLine() external returns (address); function createBorrower(address owner) external returns (address); function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256[] calldata _allowedUIDTypes ) external returns (address); function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256[] calldata _allowedUIDTypes ) external returns (address); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IGo { uint256 public constant ID_TYPE_0 = 0; uint256 public constant ID_TYPE_1 = 1; uint256 public constant ID_TYPE_2 = 2; uint256 public constant ID_TYPE_3 = 3; uint256 public constant ID_TYPE_4 = 4; uint256 public constant ID_TYPE_5 = 5; uint256 public constant ID_TYPE_6 = 6; uint256 public constant ID_TYPE_7 = 7; uint256 public constant ID_TYPE_8 = 8; uint256 public constant ID_TYPE_9 = 9; uint256 public constant ID_TYPE_10 = 10; /// @notice Returns the address of the UniqueIdentity contract. function uniqueIdentity() external virtual returns (address); function go(address account) public view virtual returns (bool); function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool); function goSeniorPool(address account) public view virtual returns (bool); function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../protocol/core/Pool.sol"; import "../protocol/core/Accountant.sol"; import "../protocol/core/CreditLine.sol"; import "../protocol/core/GoldfinchConfig.sol"; contract FakeV2CreditDesk is BaseUpgradeablePausable { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; GoldfinchConfig public config; struct Underwriter { uint256 governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentMade( address indexed payer, address indexed creditLine, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount ); event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit); event LimitChanged(address indexed owner, string limitType, uint256 amount); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; function initialize(address owner, GoldfinchConfig _config) public initializer { owner; _config; return; } function someBrandNewFunction() public pure returns (uint256) { return 5; } function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; /** * @title Goldfinch's Pool contract * @notice Main entry point for LP's (a.k.a. capital providers) * Handles key logic for depositing and withdrawing funds from the Pool * @author Goldfinch */ contract Pool is BaseUpgradeablePausable, IPool { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; uint256 public compoundBalance; event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares); event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount); event TransferMade(address indexed from, address indexed to, uint256 amount); event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount); event PrincipalCollected(address indexed payer, uint256 amount); event ReserveFundsCollected(address indexed user, uint256 amount); event PrincipalWrittendown(address indexed creditline, int256 amount); event GoldfinchConfigUpdated(address indexed who, address configAddress); /** * @notice Run only once, on initialization * @param owner The address of who should have the "OWNER_ROLE" of this contract * @param _config The address of the GoldfinchConfig contract */ function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; sharePrice = fiduMantissa(); IERC20withDec usdc = config.getUSDC(); // Sanity check the address usdc.totalSupply(); // Unlock self for infinite amount bool success = usdc.approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens * @param amount The amount of USDC to deposit */ function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant { require(amount > 0, "Must deposit more than zero"); // Check if the amount of new shares to be added is within limits uint256 depositShares = getNumShares(amount); uint256 potentialNewTotalShares = totalShares().add(depositShares); require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit."); emit DepositMade(msg.sender, amount, depositShares); bool success = doUSDCTransfer(msg.sender, address(this), amount); require(success, "Failed to transfer for deposit"); config.getFidu().mintTo(msg.sender, depositShares); } /** * @notice Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens * @param usdcAmount The amount of USDC to withdraw */ function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant { require(usdcAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 withdrawShares = getNumShares(usdcAmount); _withdraw(usdcAmount, withdrawShares); } /** * @notice Withdraws USDC (denominated in FIDU terms) from the Pool to msg.sender * @param fiduAmount The amount of USDC to withdraw in terms of fidu shares */ function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant { require(fiduAmount > 0, "Must withdraw more than zero"); if (compoundBalance > 0) { _sweepFromCompound(); } uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount); uint256 withdrawShares = fiduAmount; _withdraw(usdcAmount, withdrawShares); } /** * @notice Collects `interest` USDC in interest and `principal` in principal from `from` and sends it to the Pool. * This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address * @param from The address to take the USDC from. Implicitly, the Pool * must be authorized to move USDC on behalf of `from`. * @param interest the interest amount of USDC to move to the Pool * @param principal the principal amount of USDC to move to the Pool * * Requirements: * - The caller must be the Credit Desk. Not even the owner can call this function. */ function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public override onlyCreditDesk whenNotPaused { _collectInterestAndPrincipal(from, interest, principal); } function distributeLosses(address creditlineAddress, int256 writedownDelta) external override onlyCreditDesk whenNotPaused { if (writedownDelta > 0) { uint256 delta = usdcToSharePrice(uint256(writedownDelta)); sharePrice = sharePrice.add(delta); } else { // If delta is negative, convert to positive uint, and sub from sharePrice uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1)); sharePrice = sharePrice.sub(delta); } emit PrincipalWrittendown(creditlineAddress, writedownDelta); } /** * @notice Moves `amount` USDC from `from`, to `to`. * @param from The address to take the USDC from. Implicitly, the Pool * must be authorized to move USDC on behalf of `from`. * @param to The address that the USDC should be moved to * @param amount the amount of USDC to move to the Pool * * Requirements: * - The caller must be the Credit Desk. Not even the owner can call this function. */ function transferFrom( address from, address to, uint256 amount ) public override onlyCreditDesk whenNotPaused returns (bool) { bool result = doUSDCTransfer(from, to, amount); require(result, "USDC Transfer failed"); emit TransferMade(from, to, amount); return result; } /** * @notice Moves `amount` USDC from the pool, to `to`. This is similar to transferFrom except we sweep any * balance we have from compound first and recognize interest. Meant to be called only by the credit desk on drawdown * @param to The address that the USDC should be moved to * @param amount the amount of USDC to move to the Pool * * Requirements: * - The caller must be the Credit Desk. Not even the owner can call this function. */ function drawdown(address to, uint256 amount) public override onlyCreditDesk whenNotPaused returns (bool) { if (compoundBalance > 0) { _sweepFromCompound(); } return transferFrom(address(this), to, amount); } function assets() public view override returns (uint256) { ICreditDesk creditDesk = config.getCreditDesk(); return compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(creditDesk.totalLoansOutstanding()).sub( creditDesk.totalWritedowns() ); } function migrateToSeniorPool() external onlyAdmin { // Bring back all USDC if (compoundBalance > 0) { sweepFromCompound(); } // Pause deposits/withdrawals if (!paused()) { pause(); } // Remove special priveldges from Fidu bytes32 minterRole = keccak256("MINTER_ROLE"); bytes32 pauserRole = keccak256("PAUSER_ROLE"); config.getFidu().renounceRole(minterRole, address(this)); config.getFidu().renounceRole(pauserRole, address(this)); // Move all USDC to the SeniorPool address seniorPoolAddress = config.seniorPoolAddress(); uint256 balance = config.getUSDC().balanceOf(address(this)); bool success = doUSDCTransfer(address(this), seniorPoolAddress, balance); require(success, "Failed to transfer USDC balance to the senior pool"); // Claim our COMP! address compoundController = address(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); bytes memory data = abi.encodeWithSignature("claimComp(address)", address(this)); bytes memory _res; // solhint-disable-next-line avoid-low-level-calls (success, _res) = compoundController.call(data); require(success, "Failed to claim COMP"); // Send our balance of COMP! address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888); data = abi.encodeWithSignature("balanceOf(address)", address(this)); // solhint-disable-next-line avoid-low-level-calls (success, _res) = compToken.call(data); uint256 compBalance = toUint256(_res); data = abi.encodeWithSignature("transfer(address,uint256)", seniorPoolAddress, compBalance); // solhint-disable-next-line avoid-low-level-calls (success, _res) = compToken.call(data); require(success, "Failed to transfer COMP"); } function toUint256(bytes memory _bytes) internal pure returns (uint256 value) { assembly { value := mload(add(_bytes, 0x20)) } } /** * @notice Moves any USDC still in the Pool to Compound, and tracks the amount internally. * This is done to earn interest on latent funds until we have other borrowers who can use it. * * Requirements: * - The caller must be an admin. */ function sweepToCompound() public override onlyAdmin whenNotPaused { IERC20 usdc = config.getUSDC(); uint256 usdcBalance = usdc.balanceOf(address(this)); ICUSDCContract cUSDC = config.getCUSDCContract(); // Approve compound to the exact amount bool success = usdc.approve(address(cUSDC), usdcBalance); require(success, "Failed to approve USDC for compound"); sweepToCompound(cUSDC, usdcBalance); // Remove compound approval to be extra safe success = config.getUSDC().approve(address(cUSDC), 0); require(success, "Failed to approve USDC for compound"); } /** * @notice Moves any USDC from Compound back to the Pool, and recognizes interest earned. * This is done automatically on drawdown or withdraw, but can be called manually if necessary. * * Requirements: * - The caller must be an admin. */ function sweepFromCompound() public override onlyAdmin whenNotPaused { _sweepFromCompound(); } /* Internal Functions */ function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal withinTransactionLimit(usdcAmount) { IFidu fidu = config.getFidu(); // Determine current shares the address has and the shares requested to withdraw uint256 currentShares = fidu.balanceOf(msg.sender); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator()); uint256 userAmount = usdcAmount.sub(reserveAmount); emit WithdrawalMade(msg.sender, userAmount, reserveAmount); // Send the amounts bool success = doUSDCTransfer(address(this), msg.sender, userAmount); require(success, "Failed to transfer for withdraw"); sendToReserve(address(this), reserveAmount, msg.sender); // Burn the shares fidu.burnFrom(msg.sender, withdrawShares); } function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal { // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains // before we can add additional capital to Compound require(compoundBalance == 0, "Cannot sweep when we already have a compound balance"); require(usdcAmount != 0, "Amount to sweep cannot be zero"); uint256 error = cUSDC.mint(usdcAmount); require(error == 0, "Sweep to compound failed"); compoundBalance = usdcAmount; } function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal { uint256 cBalance = compoundBalance; require(cBalance != 0, "No funds on compound"); require(cUSDCAmount != 0, "Amount to sweep cannot be zero"); IERC20 usdc = config.getUSDC(); uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this)); uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent(); uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount); uint256 error = cUSDC.redeem(cUSDCAmount); uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this)); require(error == 0, "Sweep from compound failed"); require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount"); uint256 interestAccrued = redeemedUSDC.sub(cBalance); _collectInterestAndPrincipal(address(this), interestAccrued, 0); compoundBalance = 0; } function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal { uint256 reserveAmount = interest.div(config.getReserveDenominator()); uint256 poolAmount = interest.sub(reserveAmount); uint256 increment = usdcToSharePrice(poolAmount); sharePrice = sharePrice.add(increment); if (poolAmount > 0) { emit InterestCollected(from, poolAmount, reserveAmount); } if (principal > 0) { emit PrincipalCollected(from, principal); } if (reserveAmount > 0) { sendToReserve(from, reserveAmount, from); } // Gas savings: No need to transfer to yourself, which happens in sweepFromCompound if (from != address(this)) { bool success = doUSDCTransfer(from, address(this), principal.add(poolAmount)); require(success, "Failed to collect principal repayment"); } } function _sweepFromCompound() internal { ICUSDCContract cUSDC = config.getCUSDCContract(); sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this))); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function usdcToFidu(uint256 amount) internal pure returns (uint256) { return amount.mul(fiduMantissa()).div(usdcMantissa()); } function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) { // See https://compound.finance/docs#protocol-math // But note, the docs and reality do not agree. Docs imply that that exchange rate is // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16 // 1e16 is also what Sheraz at Certik said. uint256 usdcDecimals = 6; uint256 cUSDCDecimals = 8; // We multiply in the following order, for the following reasons... // Amount in cToken (1e8) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are) // Downscale to cToken decimals (1e8) // Downscale from cToken to USDC decimals (8 to 6) return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2); } function totalShares() internal view returns (uint256) { return config.getFidu().totalSupply(); } function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) { return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares()); } function poolWithinLimit(uint256 _totalShares) internal view returns (bool) { return _totalShares.mul(sharePrice).div(fiduMantissa()) <= usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit))); } function transactionWithinLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit)); } function getNumShares(uint256 amount) internal view returns (uint256) { return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice); } function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) { return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa())); } function fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(fiduMantissa().div(usdcMantissa())); } function sendToReserve( address from, uint256 amount, address userForEvent ) internal { emit ReserveFundsCollected(userForEvent, amount); bool success = doUSDCTransfer(from, config.reserveAddress(), amount); require(success, "Reserve transfer was not successful"); } function doUSDCTransfer( address from, address to, uint256 amount ) internal returns (bool) { require(to != address(0), "Can't send to zero address"); IERC20withDec usdc = config.getUSDC(); return usdc.transferFrom(from, to, amount); } modifier withinTransactionLimit(uint256 amount) { require(transactionWithinLimit(amount), "Amount is over the per-transaction limit"); _; } modifier onlyCreditDesk() { require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./CreditLine.sol"; import "../../interfaces/ICreditLine.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title The Accountant * @notice Library for handling key financial calculations, such as interest and principal accrual. * @author Goldfinch */ library Accountant { using SafeMath for uint256; using FixedPoint for FixedPoint.Signed; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for int256; using FixedPoint for uint256; // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled uint256 public constant FP_SCALING_FACTOR = 10**18; uint256 public constant INTEREST_DECIMALS = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365); struct PaymentAllocation { uint256 interestPayment; uint256 principalPayment; uint256 additionalBalancePayment; } function calculateInterestAndPrincipalAccrued( CreditLine cl, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 balance = cl.balance(); // gas optimization uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp); return (interestAccrued, principalAccrued); } function calculateInterestAndPrincipalAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime); return (interestAccrued, principalAccrued); } function calculatePrincipalAccrued( ICreditLine cl, uint256 balance, uint256 timestamp ) public view returns (uint256) { // If we've already accrued principal as of the term end time, then don't accrue more principal uint256 termEndTime = cl.termEndTime(); if (cl.interestAccruedAsOf() >= termEndTime) { return 0; } if (timestamp >= termEndTime) { return balance; } else { return 0; } } function calculateWritedownFor( ICreditLine cl, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate); } function calculateWritedownForPrincipal( ICreditLine cl, uint256 principal, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl); if (amountOwedPerDay.isEqual(0)) { return (0, 0); } FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays); FixedPoint.Unsigned memory daysLate; // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30, // Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to // calculate the periods later. uint256 totalOwed = cl.interestOwed().add(cl.principalOwed()); daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay); if (timestamp > cl.termEndTime()) { uint256 secondsLate = timestamp.sub(cl.termEndTime()); daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY)); } FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate); FixedPoint.Unsigned memory writedownPercent; if (daysLate.isLessThanOrEqual(fpGracePeriod)) { // Within the grace period, we don't have to write down, so assume 0% writedownPercent = FixedPoint.fromUnscaledUint(0); } else { writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate)); } FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR); // This will return a number between 0-100 representing the write down percent with no decimals uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue; return (unscaledWritedownPercent, writedownAmount.rawValue); } function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) { // Determine theoretical interestOwed for one full day uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365); return interestOwed; } function calculateInterestAccrued( CreditLine cl, uint256 balance, uint256 timestamp, uint256 lateFeeGracePeriodInDays ) public view returns (uint256) { // We use Math.min here to prevent integer overflow (ie. go negative) when calculating // numSecondsElapsed. Typically this shouldn't be possible, because // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing // we allow this function to be called with a past timestamp, which raises the possibility // of overflow. // This use of min should not generate incorrect interest calculations, since // this function's purpose is just to normalize balances, and handing in a past timestamp // will necessarily return zero interest accrued (because zero elapsed time), which is correct. uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays); } function calculateInterestAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriodInDays ) public view returns (uint256 interestOwed) { uint256 secondsElapsed = endTime.sub(startTime); uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) { uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS); uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); interestOwed = interestOwed.add(additionalLateFeeInterest); } return interestOwed; } function lateFeeApplicable( CreditLine cl, uint256 timestamp, uint256 gracePeriodInDays ) public view returns (bool) { uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime()); return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY); } function allocatePayment( uint256 paymentAmount, uint256 balance, uint256 interestOwed, uint256 principalOwed ) public pure returns (PaymentAllocation memory) { uint256 paymentRemaining = paymentAmount; uint256 interestPayment = Math.min(interestOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(interestPayment); uint256 principalPayment = Math.min(principalOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(principalPayment); uint256 balanceRemaining = balance.sub(principalPayment); uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining); return PaymentAllocation({ interestPayment: interestPayment, principalPayment: principalPayment, additionalBalancePayment: additionalBalancePayment }); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "./BaseUpgradeablePausable.sol"; import "./Accountant.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICreditLine.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; /** * @title CreditLine * @notice A contract that represents the agreement between Backers and * a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed. * A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not * operate in any standalone capacity. It should generally be considered internal to the TranchedPool. * @author Goldfinch */ // solhint-disable-next-line max-states-count contract CreditLine is BaseUpgradeablePausable, ICreditLine { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; event GoldfinchConfigUpdated(address indexed who, address configAddress); // Credit line terms address public override borrower; uint256 public currentLimit; uint256 public override maxLimit; uint256 public override interestApr; uint256 public override paymentPeriodInDays; uint256 public override termInDays; uint256 public override principalGracePeriodInDays; uint256 public override lateFeeApr; // Accounting variables uint256 public override balance; uint256 public override interestOwed; uint256 public override principalOwed; uint256 public override termEndTime; uint256 public override nextDueTime; uint256 public override interestAccruedAsOf; uint256 public override lastFullPaymentTime; uint256 public totalInterestAccrued; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; function initialize( address _config, address owner, address _borrower, uint256 _maxLimit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public initializer { require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); borrower = _borrower; maxLimit = _maxLimit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; principalGracePeriodInDays = _principalGracePeriodInDays; interestAccruedAsOf = block.timestamp; // Unlock owner, which is a TranchedPool, for infinite amount bool success = config.getUSDC().approve(owner, uint256(-1)); require(success, "Failed to approve USDC"); } function limit() external view override returns (uint256) { return currentLimit; } /** * @notice Updates the internal accounting to track a drawdown as of current block timestamp. * Does not move any money * @param amount The amount in USDC that has been drawndown */ function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit"); require(amount > 0, "Invalid drawdown amount"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!_isLate(timestamp), "Cannot drawdown when payments are past due"); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin { lateFeeApr = newLateFeeApr; } function setLimit(uint256 newAmount) external onlyAdmin { require(newAmount <= maxLimit, "Cannot be more than the max limit"); currentLimit = newAmount; } function setMaxLimit(uint256 newAmount) external onlyAdmin { maxLimit = newAmount; } function termStartTime() external view returns (uint256) { return _termStartTime(); } function isLate() external view override returns (bool) { return _isLate(block.timestamp); } function withinPrincipalGracePeriod() external view override returns (bool) { if (termEndTime == 0) { // Loan hasn't started yet return true; } return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY)); } function setTermEndTime(uint256 newTermEndTime) public onlyAdmin { termEndTime = newTermEndTime; } function setNextDueTime(uint256 newNextDueTime) public onlyAdmin { nextDueTime = newNextDueTime; } function setBalance(uint256 newBalance) public onlyAdmin { balance = newBalance; } function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin { totalInterestAccrued = _totalInterestAccrued; } function setInterestOwed(uint256 newInterestOwed) public onlyAdmin { interestOwed = newInterestOwed; } function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin { principalOwed = newPrincipalOwed; } function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin { interestAccruedAsOf = newInterestAccruedAsOf; } function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin { lastFullPaymentTime = newLastFullPaymentTime; } /** * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied * towards the interest and principal. * @return Any amount remaining after applying payments towards the interest and principal * @return Amount applied towards interest * @return Amount applied towards principal */ function assess() public onlyAdmin returns ( uint256, uint256, uint256 ) { // Do not assess until a full period has elapsed or past due require(balance > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < nextDueTime && !_isLate(currentTime())) { return (0, 0, 0); } uint256 timeToAssess = calculateNextDueTime(); setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } return handlePayment(getUSDCBalance(address(this)), timeToAssess); } function calculateNextDueTime() internal view returns (uint256) { uint256 newNextDueTime = nextDueTime; uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (newNextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* newNextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= newNextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); newNextDueTime = newNextDueTime.add(secondsToAdvance); return Math.min(newNextDueTime, termEndTime); } // You're paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && newNextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the newNextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < newNextDueTime) { return newNextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function _isLate(uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime); return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY); } function _termStartTime() internal view returns (uint256) { return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays)); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param paymentAmount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function handlePayment(uint256 paymentAmount, uint256 timestamp) internal returns ( uint256, uint256, uint256 ) { (uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, balance, newInterestOwed, newPrincipalOwed ); uint256 newBalance = balance.sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = balance.sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( newBalance, newInterestOwed.sub(pa.interestPayment), newPrincipalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( this, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. setInterestAccruedAsOf(timestamp); totalInterestAccrued = totalInterestAccrued.add(interestAccrued); } return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued)); } function updateCreditLineAccounting( uint256 newBalance, uint256 newInterestOwed, uint256 newPrincipalOwed ) internal nonReentrant { setBalance(newBalance); setInterestOwed(newInterestOwed); setPrincipalOwed(newPrincipalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 _nextDueTime = nextDueTime; if (newInterestOwed == 0 && _nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < _nextDueTime) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = _nextDueTime; } setLastFullPaymentTime(mostRecentLastDueTime); } setNextDueTime(calculateNextDueTime()); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } } // SPDX-License-Identifier: AGPL-3.0-only // solhint-disable // Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IERC20withDec.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/TranchedPool.sol"; contract TestTranchedPool is TranchedPool { function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public { collectInterestAndPrincipal(from, interest, principal); } function _setSeniorTranchePrincipalDeposited(uint256 principalDeposited) public { poolSlices[poolSlices.length - 1].seniorTranche.principalDeposited = principalDeposited; } function _setLimit(uint256 limit) public { creditLine.setLimit(limit); } function _modifyJuniorTrancheLockedUntil(uint256 lockedUntil) public { poolSlices[poolSlices.length - 1].juniorTranche.lockedUntil = lockedUntil; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/IV2CreditLine.sol"; import "../../interfaces/IPoolTokens.sol"; import "./GoldfinchConfig.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../library/SafeERC20Transfer.sol"; import "./TranchingLogic.sol"; contract TranchedPool is BaseUpgradeablePausable, ITranchedPool, SafeERC20Transfer { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using TranchingLogic for PoolSlice; using TranchingLogic for TrancheInfo; bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE"); bytes32 public constant SENIOR_ROLE = keccak256("SENIOR_ROLE"); uint256 public constant FP_SCALING_FACTOR = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100 uint256 public constant NUM_TRANCHES_PER_SLICE = 2; uint256 public juniorFeePercent; bool public drawdownsPaused; uint256[] public allowedUIDTypes; uint256 public totalDeployed; uint256 public fundableAt; PoolSlice[] public poolSlices; event DepositMade(address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 amount); event WithdrawalMade( address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 interestWithdrawn, uint256 principalWithdrawn ); event GoldfinchConfigUpdated(address indexed who, address configAddress); event TranchedPoolAssessed(address indexed pool); event PaymentApplied( address indexed payer, address indexed pool, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount, uint256 reserveAmount ); // Note: This has to exactly match the even in the TranchingLogic library for events to be emitted // correctly event SharePriceUpdated( address indexed pool, uint256 indexed tranche, uint256 principalSharePrice, int256 principalDelta, uint256 interestSharePrice, int256 interestDelta ); event ReserveFundsCollected(address indexed from, uint256 amount); event CreditLineMigrated(address indexed oldCreditLine, address indexed newCreditLine); event DrawdownMade(address indexed borrower, uint256 amount); event DrawdownsPaused(address indexed pool); event DrawdownsUnpaused(address indexed pool); event EmergencyShutdown(address indexed pool); event TrancheLocked(address indexed pool, uint256 trancheId, uint256 lockedUntil); event SliceCreated(address indexed pool, uint256 sliceId); function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) public override initializer { require(address(_config) != address(0) && address(_borrower) != address(0), "Config/borrower invalid"); config = GoldfinchConfig(_config); address owner = config.protocolAdminAddress(); require(owner != address(0), "Owner invalid"); __BaseUpgradeablePausable__init(owner); _initializeNextSlice(_fundableAt); createAndSetCreditLine( _borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays ); createdAt = block.timestamp; juniorFeePercent = _juniorFeePercent; if (_allowedUIDTypes.length == 0) { uint256[1] memory defaultAllowedUIDTypes = [config.getGo().ID_TYPE_0()]; allowedUIDTypes = defaultAllowedUIDTypes; } else { allowedUIDTypes = _allowedUIDTypes; } _setupRole(LOCKER_ROLE, _borrower); _setupRole(LOCKER_ROLE, owner); _setRoleAdmin(LOCKER_ROLE, OWNER_ROLE); _setRoleAdmin(SENIOR_ROLE, OWNER_ROLE); // Give the senior pool the ability to deposit into the senior pool _setupRole(SENIOR_ROLE, address(config.getSeniorPool())); // Unlock self for infinite amount bool success = config.getUSDC().approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } function setAllowedUIDTypes(uint256[] calldata ids) public onlyLocker { require( poolSlices[0].juniorTranche.principalDeposited == 0 && poolSlices[0].seniorTranche.principalDeposited == 0, "Must not have balance" ); allowedUIDTypes = ids; } /** * @notice Deposit a USDC amount into the pool for a tranche. Mints an NFT to the caller representing the position * @param tranche The number representing the tranche to deposit into * @param amount The USDC amount to tranfer from the caller to the pool * @return tokenId The tokenId of the NFT */ function deposit(uint256 tranche, uint256 amount) public override nonReentrant whenNotPaused returns (uint256 tokenId) { TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche locked"); require(amount > 0, "Must deposit > zero"); require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed"); require(block.timestamp > fundableAt, "Not open for funding"); // senior tranche ids are always odd numbered if (_isSeniorTrancheId(trancheInfo.id)) { require(hasRole(SENIOR_ROLE, _msgSender()), "Req SENIOR_ROLE"); } trancheInfo.principalDeposited = trancheInfo.principalDeposited.add(amount); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({tranche: tranche, principalAmount: amount}); tokenId = config.getPoolTokens().mint(params, msg.sender); safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); emit DepositMade(msg.sender, tranche, tokenId, amount); return tokenId; } function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 tokenId) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(tranche, amount); } /** * @notice Withdraw an already deposited amount if the funds are available * @param tokenId The NFT representing the position * @param amount The amount to withdraw (must be <= interest+principal currently available to withdraw) * @return interestWithdrawn The interest amount that was withdrawn * @return principalWithdrawn The principal amount that was withdrawn */ function withdraw(uint256 tokenId, uint256 amount) public override nonReentrant whenNotPaused returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); return _withdraw(trancheInfo, tokenInfo, tokenId, amount); } /** * @notice Withdraw from many tokens (that the sender owns) in a single transaction * @param tokenIds An array of tokens ids representing the position * @param amounts An array of amounts to withdraw from the corresponding tokenIds */ function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) public override { require(tokenIds.length == amounts.length, "TokensIds and Amounts mismatch"); for (uint256 i = 0; i < amounts.length; i++) { withdraw(tokenIds[i], amounts[i]); } } /** * @notice Similar to withdraw but will withdraw all available funds * @param tokenId The NFT representing the position * @return interestWithdrawn The interest amount that was withdrawn * @return principalWithdrawn The principal amount that was withdrawn */ function withdrawMax(uint256 tokenId) external override nonReentrant whenNotPaused returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); (uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo); uint256 amount = interestRedeemable.add(principalRedeemable); return _withdraw(trancheInfo, tokenInfo, tokenId, amount); } /** * @notice Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower * @param amount The amount to drawdown from the creditline (must be < limit) */ function drawdown(uint256 amount) external override onlyLocker whenNotPaused { require(!drawdownsPaused, "Drawdowns are paused"); if (!locked()) { // Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool) _lockPool(); } // Drawdown only draws down from the current slice for simplicity. It's harder to account for how much // money is available from previous slices since depositors can redeem after unlock. PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)]; uint256 amountAvailable = sharePriceToUsdc( currentSlice.juniorTranche.principalSharePrice, currentSlice.juniorTranche.principalDeposited ); amountAvailable = amountAvailable.add( sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited) ); require(amount <= amountAvailable, "Insufficient funds in slice"); creditLine.drawdown(amount); // Update the share price to reflect the amount remaining in the pool uint256 amountRemaining = amountAvailable.sub(amount); uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice; uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice; currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount); totalDeployed = totalDeployed.add(amount); address borrower = creditLine.borrower(); safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount); emit DrawdownMade(borrower, amount); emit SharePriceUpdated( address(this), currentSlice.juniorTranche.id, currentSlice.juniorTranche.principalSharePrice, int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1, currentSlice.juniorTranche.interestSharePrice, 0 ); emit SharePriceUpdated( address(this), currentSlice.seniorTranche.id, currentSlice.seniorTranche.principalSharePrice, int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1, currentSlice.seniorTranche.interestSharePrice, 0 ); } /** * @notice Locks the junior tranche, preventing more junior deposits. Gives time for the senior to determine how * much to invest (ensure leverage ratio cannot change for the period) */ function lockJuniorCapital() external override onlyLocker whenNotPaused { _lockJuniorCapital(poolSlices.length.sub(1)); } /** * @notice Locks the pool (locks both senior and junior tranches and starts the drawdown period). Beyond the drawdown * period, any unused capital is available to withdraw by all depositors */ function lockPool() external override onlyLocker whenNotPaused { _lockPool(); } function setFundableAt(uint256 newFundableAt) external override onlyLocker { fundableAt = newFundableAt; } function initializeNextSlice(uint256 _fundableAt) external override onlyLocker whenNotPaused { require(locked(), "Current slice still active"); require(!creditLine.isLate(), "Creditline is late"); require(creditLine.withinPrincipalGracePeriod(), "Beyond principal grace period"); _initializeNextSlice(_fundableAt); emit SliceCreated(address(this), poolSlices.length.sub(1)); } /** * @notice Triggers an assessment of the creditline and the applies the payments according the tranche waterfall */ function assess() external override whenNotPaused { _assess(); } /** * @notice Allows repaying the creditline. Collects the USDC amount from the sender and triggers an assess * @param amount The amount to repay */ function pay(uint256 amount) external override whenNotPaused { require(amount > 0, "Must pay more than zero"); collectPayment(amount); _assess(); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); creditLine.updateGoldfinchConfig(); emit GoldfinchConfigUpdated(msg.sender, address(config)); } /** * @notice Pauses the pool and sweeps any remaining funds to the treasury reserve. */ function emergencyShutdown() public onlyAdmin { if (!paused()) { pause(); } IERC20withDec usdc = config.getUSDC(); address reserveAddress = config.reserveAddress(); // Sweep any funds to community reserve uint256 poolBalance = usdc.balanceOf(address(this)); if (poolBalance > 0) { safeERC20Transfer(usdc, reserveAddress, poolBalance); } uint256 clBalance = usdc.balanceOf(address(creditLine)); if (clBalance > 0) { safeERC20TransferFrom(usdc, address(creditLine), reserveAddress, clBalance); } emit EmergencyShutdown(address(this)); } /** * @notice Pauses all drawdowns (but not deposits/withdraws) */ function pauseDrawdowns() public onlyAdmin { drawdownsPaused = true; emit DrawdownsPaused(address(this)); } /** * @notice Unpause drawdowns */ function unpauseDrawdowns() public onlyAdmin { drawdownsPaused = false; emit DrawdownsUnpaused(address(this)); } /** * @notice Migrates the accounting variables from the current creditline to a brand new one * @param _borrower The borrower address * @param _maxLimit The new max limit * @param _interestApr The new interest APR * @param _paymentPeriodInDays The new payment period in days * @param _termInDays The new term in days * @param _lateFeeApr The new late fee APR */ function migrateCreditLine( address _borrower, uint256 _maxLimit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public onlyAdmin { require(_borrower != address(0), "Borrower must not be empty"); require(_paymentPeriodInDays != 0, "Payment period invalid"); require(_termInDays != 0, "Term must not be empty"); address originalClAddr = address(creditLine); createAndSetCreditLine( _borrower, _maxLimit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays ); address newClAddr = address(creditLine); TranchingLogic.migrateAccountingVariables(originalClAddr, newClAddr); TranchingLogic.closeCreditLine(originalClAddr); address originalBorrower = IV2CreditLine(originalClAddr).borrower(); address newBorrower = IV2CreditLine(newClAddr).borrower(); // Ensure Roles if (originalBorrower != newBorrower) { revokeRole(LOCKER_ROLE, originalBorrower); grantRole(LOCKER_ROLE, newBorrower); } // Transfer any funds to new CL uint256 clBalance = config.getUSDC().balanceOf(originalClAddr); if (clBalance > 0) { safeERC20TransferFrom(config.getUSDC(), originalClAddr, newClAddr, clBalance); } emit CreditLineMigrated(originalClAddr, newClAddr); } /** * @notice Migrates to a new creditline without copying the accounting variables */ function migrateAndSetNewCreditLine(address newCl) public onlyAdmin { require(newCl != address(0), "Creditline cannot be empty"); address originalClAddr = address(creditLine); // Transfer any funds to new CL uint256 clBalance = config.getUSDC().balanceOf(originalClAddr); if (clBalance > 0) { safeERC20TransferFrom(config.getUSDC(), originalClAddr, newCl, clBalance); } TranchingLogic.closeCreditLine(originalClAddr); // set new CL creditLine = IV2CreditLine(newCl); // sanity check that the new address is in fact a creditline creditLine.limit(); emit CreditLineMigrated(originalClAddr, address(creditLine)); } // CreditLine proxy method function setLimit(uint256 newAmount) external onlyAdmin { return creditLine.setLimit(newAmount); } function setMaxLimit(uint256 newAmount) external onlyAdmin { return creditLine.setMaxLimit(newAmount); } function getTranche(uint256 tranche) public view override returns (TrancheInfo memory) { return getTrancheInfo(tranche); } function numSlices() public view returns (uint256) { return poolSlices.length; } /** * @notice Converts USDC amounts to share price * @param amount The USDC amount to convert * @param totalShares The total shares outstanding * @return The share price of the input amount */ function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) { return TranchingLogic.usdcToSharePrice(amount, totalShares); } /** * @notice Converts share price to USDC amounts * @param sharePrice The share price to convert * @param totalShares The total shares outstanding * @return The USDC amount of the input share price */ function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) { return TranchingLogic.sharePriceToUsdc(sharePrice, totalShares); } /** * @notice Returns the total junior capital deposited * @return The total USDC amount deposited into all junior tranches */ function totalJuniorDeposits() external view override returns (uint256) { uint256 total; for (uint256 i = 0; i < poolSlices.length; i++) { total = total.add(poolSlices[i].juniorTranche.principalDeposited); } return total; } /** * @notice Determines the amount of interest and principal redeemable by a particular tokenId * @param tokenId The token representing the position * @return interestRedeemable The interest available to redeem * @return principalRedeemable The principal available to redeem */ function availableToWithdraw(uint256 tokenId) public view override returns (uint256 interestRedeemable, uint256 principalRedeemable) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); if (currentTime() > trancheInfo.lockedUntil) { return redeemableInterestAndPrincipal(trancheInfo, tokenInfo); } else { return (0, 0); } } /* Internal functions */ function _withdraw( TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo, uint256 tokenId, uint256 amount ) internal returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { require(config.getPoolTokens().isApprovedOrOwner(msg.sender, tokenId), "Not token owner"); require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed"); require(amount > 0, "Must withdraw more than zero"); (uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo); uint256 netRedeemable = interestRedeemable.add(principalRedeemable); require(amount <= netRedeemable, "Invalid redeem amount"); require(currentTime() > trancheInfo.lockedUntil, "Tranche is locked"); // If the tranche has not been locked, ensure the deposited amount is correct if (trancheInfo.lockedUntil == 0) { trancheInfo.principalDeposited = trancheInfo.principalDeposited.sub(amount); } uint256 interestToRedeem = Math.min(interestRedeemable, amount); uint256 principalToRedeem = Math.min(principalRedeemable, amount.sub(interestToRedeem)); config.getPoolTokens().redeem(tokenId, principalToRedeem, interestToRedeem); safeERC20TransferFrom(config.getUSDC(), address(this), msg.sender, principalToRedeem.add(interestToRedeem)); emit WithdrawalMade(msg.sender, tokenInfo.tranche, tokenId, interestToRedeem, principalToRedeem); return (interestToRedeem, principalToRedeem); } function _isSeniorTrancheId(uint256 trancheId) internal pure returns (bool) { return trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1; } function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo) internal view returns (uint256 interestRedeemable, uint256 principalRedeemable) { // This supports withdrawing before or after locking because principal share price starts at 1 // and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount); // The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a // percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1. uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount); interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed); principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed); return (interestRedeemable, principalRedeemable); } function _lockJuniorCapital(uint256 sliceId) internal { require(!locked(), "Pool already locked"); require(poolSlices[sliceId].juniorTranche.lockedUntil == 0, "Junior tranche already locked"); uint256 lockedUntil = currentTime().add(config.getDrawdownPeriodInSeconds()); poolSlices[sliceId].juniorTranche.lockedUntil = lockedUntil; emit TrancheLocked(address(this), poolSlices[sliceId].juniorTranche.id, lockedUntil); } function _lockPool() internal { uint256 sliceId = poolSlices.length.sub(1); require(poolSlices[sliceId].juniorTranche.lockedUntil > 0, "Junior tranche must be locked"); // Allow locking the pool only once; do not allow extending the lock of an // already-locked pool. Otherwise the locker could keep the pool locked // indefinitely, preventing withdrawals. require(poolSlices[sliceId].seniorTranche.lockedUntil == 0, "Lock cannot be extended"); uint256 currentTotal = poolSlices[sliceId].juniorTranche.principalDeposited.add( poolSlices[sliceId].seniorTranche.principalDeposited ); creditLine.setLimit(Math.min(creditLine.limit().add(currentTotal), creditLine.maxLimit())); // We start the drawdown period, so backers can withdraw unused capital after borrower draws down uint256 lockPeriod = config.getDrawdownPeriodInSeconds(); poolSlices[sliceId].seniorTranche.lockedUntil = currentTime().add(lockPeriod); poolSlices[sliceId].juniorTranche.lockedUntil = currentTime().add(lockPeriod); emit TrancheLocked( address(this), poolSlices[sliceId].seniorTranche.id, poolSlices[sliceId].seniorTranche.lockedUntil ); emit TrancheLocked( address(this), poolSlices[sliceId].juniorTranche.id, poolSlices[sliceId].juniorTranche.lockedUntil ); } function _initializeNextSlice(uint256 newFundableAt) internal { uint256 numSlices = poolSlices.length; require(numSlices < 5, "Cannot exceed 5 slices"); poolSlices.push( PoolSlice({ seniorTranche: TrancheInfo({ id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(1), principalSharePrice: usdcToSharePrice(1, 1), interestSharePrice: 0, principalDeposited: 0, lockedUntil: 0 }), juniorTranche: TrancheInfo({ id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(2), principalSharePrice: usdcToSharePrice(1, 1), interestSharePrice: 0, principalDeposited: 0, lockedUntil: 0 }), totalInterestAccrued: 0, principalDeployed: 0 }) ); fundableAt = newFundableAt; } function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal returns (uint256 totalReserveAmount) { safeERC20TransferFrom(config.getUSDC(), from, address(this), principal.add(interest), "Failed to collect payment"); uint256 reserveFeePercent = ONE_HUNDRED.div(config.getReserveDenominator()); // Convert the denonminator to percent ApplyResult memory result = TranchingLogic.applyToAllSeniorTranches( poolSlices, interest, principal, reserveFeePercent, totalDeployed, creditLine, juniorFeePercent ); totalReserveAmount = result.reserveDeduction.add( TranchingLogic.applyToAllJuniorTranches( poolSlices, result.interestRemaining, result.principalRemaining, reserveFeePercent, totalDeployed, creditLine ) ); sendToReserve(totalReserveAmount); return totalReserveAmount; } // If the senior tranche of the current slice is locked, then the pool is not open to any more deposits // (could throw off leverage ratio) function locked() internal view returns (bool) { return poolSlices[poolSlices.length.sub(1)].seniorTranche.lockedUntil > 0; } function createAndSetCreditLine( address _borrower, uint256 _maxLimit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) internal { address _creditLine = config.getGoldfinchFactory().createCreditLine(); creditLine = IV2CreditLine(_creditLine); creditLine.initialize( address(config), address(this), // Set self as the owner _borrower, _maxLimit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays ); } function getTrancheInfo(uint256 trancheId) internal view returns (TrancheInfo storage) { require(trancheId > 0 && trancheId <= poolSlices.length.mul(NUM_TRANCHES_PER_SLICE), "Unsupported tranche"); uint256 sliceId = ((trancheId.add(trancheId.mod(NUM_TRANCHES_PER_SLICE))).div(NUM_TRANCHES_PER_SLICE)).sub(1); PoolSlice storage slice = poolSlices[sliceId]; TrancheInfo storage trancheInfo = trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1 ? slice.seniorTranche : slice.juniorTranche; return trancheInfo; } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function sendToReserve(uint256 amount) internal { emit ReserveFundsCollected(address(this), amount); safeERC20TransferFrom( config.getUSDC(), address(this), config.reserveAddress(), amount, "Failed to send to reserve" ); } function collectPayment(uint256 amount) internal { safeERC20TransferFrom(config.getUSDC(), msg.sender, address(creditLine), amount, "Failed to collect payment"); } function _assess() internal { // We need to make sure the pool is locked before we allocate rewards to ensure it's not // possible to game rewards by sandwiching an interest payment to an unlocked pool // It also causes issues trying to allocate payments to an empty slice (divide by zero) require(locked(), "Pool is not locked"); uint256 interestAccrued = creditLine.totalInterestAccrued(); (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = creditLine.assess(); interestAccrued = creditLine.totalInterestAccrued().sub(interestAccrued); // Split the interest accrued proportionally across slices so we know how much interest goes to each slice // We need this because the slice start at different times, so we cannot retroactively allocate the interest // linearly uint256[] memory principalPaymentsPerSlice = new uint256[](poolSlices.length); for (uint256 i = 0; i < poolSlices.length; i++) { uint256 interestForSlice = TranchingLogic.scaleByFraction( interestAccrued, poolSlices[i].principalDeployed, totalDeployed ); principalPaymentsPerSlice[i] = TranchingLogic.scaleByFraction( principalPayment, poolSlices[i].principalDeployed, totalDeployed ); poolSlices[i].totalInterestAccrued = poolSlices[i].totalInterestAccrued.add(interestForSlice); } if (interestPayment > 0 || principalPayment > 0) { uint256 reserveAmount = collectInterestAndPrincipal( address(creditLine), interestPayment, principalPayment.add(paymentRemaining) ); for (uint256 i = 0; i < poolSlices.length; i++) { poolSlices[i].principalDeployed = poolSlices[i].principalDeployed.sub(principalPaymentsPerSlice[i]); totalDeployed = totalDeployed.sub(principalPaymentsPerSlice[i]); } config.getBackerRewards().allocateRewards(interestPayment); emit PaymentApplied( creditLine.borrower(), address(this), interestPayment, principalPayment, paymentRemaining, reserveAmount ); } emit TranchedPoolAssessed(address(this)); } modifier onlyLocker() { require(hasRole(LOCKER_ROLE, msg.sender), "Must have locker role"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /** * @title Safe ERC20 Transfer * @notice Reverts when transfer is not successful * @author Goldfinch */ abstract contract SafeERC20Transfer { function safeERC20Transfer( IERC20 erc20, address to, uint256 amount, string memory message ) internal { require(to != address(0), "Can't send to zero address"); bool success = erc20.transfer(to, amount); require(success, message); } function safeERC20Transfer( IERC20 erc20, address to, uint256 amount ) internal { safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20"); } function safeERC20TransferFrom( IERC20 erc20, address from, address to, uint256 amount, string memory message ) internal { require(to != address(0), "Can't send to zero address"); bool success = erc20.transferFrom(from, to, amount); require(success, message); } function safeERC20TransferFrom( IERC20 erc20, address from, address to, uint256 amount ) internal { string memory message = "Failed to transfer ERC20"; safeERC20TransferFrom(erc20, from, to, amount, message); } function safeERC20Approve( IERC20 erc20, address spender, uint256 allowance, string memory message ) internal { bool success = erc20.approve(spender, allowance); require(success, message); } function safeERC20Approve( IERC20 erc20, address spender, uint256 allowance ) internal { string memory message = "Failed to approve ERC20"; safeERC20Approve(erc20, spender, allowance, message); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IV2CreditLine.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title TranchingLogic * @notice Library for handling the payments waterfall * @author Goldfinch */ library TranchingLogic { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; event SharePriceUpdated( address indexed pool, uint256 indexed tranche, uint256 principalSharePrice, int256 principalDelta, uint256 interestSharePrice, int256 interestDelta ); uint256 public constant FP_SCALING_FACTOR = 1e18; uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100 function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) { return totalShares == 0 ? 0 : amount.mul(FP_SCALING_FACTOR).div(totalShares); } function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) { return sharePrice.mul(totalShares).div(FP_SCALING_FACTOR); } function redeemableInterestAndPrincipal( ITranchedPool.TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo ) public view returns (uint256 interestRedeemable, uint256 principalRedeemable) { // This supports withdrawing before or after locking because principal share price starts at 1 // and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount); // The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a // percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1. uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount); interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed); principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed); return (interestRedeemable, principalRedeemable); } function calculateExpectedSharePrice( ITranchedPool.TrancheInfo memory tranche, uint256 amount, ITranchedPool.PoolSlice memory slice ) public pure returns (uint256) { uint256 sharePrice = usdcToSharePrice(amount, tranche.principalDeposited); return scaleByPercentOwnership(tranche, sharePrice, slice); } function scaleForSlice( ITranchedPool.PoolSlice memory slice, uint256 amount, uint256 totalDeployed ) public pure returns (uint256) { return scaleByFraction(amount, slice.principalDeployed, totalDeployed); } // We need to create this struct so we don't run into a stack too deep error due to too many variables function getSliceInfo( ITranchedPool.PoolSlice memory slice, IV2CreditLine creditLine, uint256 totalDeployed, uint256 reserveFeePercent ) public view returns (ITranchedPool.SliceInfo memory) { (uint256 interestAccrued, uint256 principalAccrued) = getTotalInterestAndPrincipal( slice, creditLine, totalDeployed ); return ITranchedPool.SliceInfo({ reserveFeePercent: reserveFeePercent, interestAccrued: interestAccrued, principalAccrued: principalAccrued }); } function getTotalInterestAndPrincipal( ITranchedPool.PoolSlice memory slice, IV2CreditLine creditLine, uint256 totalDeployed ) public view returns (uint256 interestAccrued, uint256 principalAccrued) { principalAccrued = creditLine.principalOwed(); // In addition to principal actually owed, we need to account for early principal payments // If the borrower pays back 5K early on a 10K loan, the actual principal accrued should be // 5K (balance- deployed) + 0 (principal owed) principalAccrued = totalDeployed.sub(creditLine.balance()).add(principalAccrued); // Now we need to scale that correctly for the slice we're interested in principalAccrued = scaleForSlice(slice, principalAccrued, totalDeployed); // Finally, we need to account for partial drawdowns. e.g. If 20K was deposited, and only 10K was drawn down, // Then principal accrued should start at 10K (total deposited - principal deployed), not 0. This is because // share price starts at 1, and is decremented by what was drawn down. uint256 totalDeposited = slice.seniorTranche.principalDeposited.add(slice.juniorTranche.principalDeposited); principalAccrued = totalDeposited.sub(slice.principalDeployed).add(principalAccrued); return (slice.totalInterestAccrued, principalAccrued); } function scaleByFraction( uint256 amount, uint256 fraction, uint256 total ) public pure returns (uint256) { FixedPoint.Unsigned memory totalAsFixedPoint = FixedPoint.fromUnscaledUint(total); FixedPoint.Unsigned memory fractionAsFixedPoint = FixedPoint.fromUnscaledUint(fraction); return fractionAsFixedPoint.div(totalAsFixedPoint).mul(amount).div(FP_SCALING_FACTOR).rawValue; } function applyToAllSeniorTranches( ITranchedPool.PoolSlice[] storage poolSlices, uint256 interest, uint256 principal, uint256 reserveFeePercent, uint256 totalDeployed, IV2CreditLine creditLine, uint256 juniorFeePercent ) public returns (ITranchedPool.ApplyResult memory) { ITranchedPool.ApplyResult memory seniorApplyResult; for (uint256 i = 0; i < poolSlices.length; i++) { ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo( poolSlices[i], creditLine, totalDeployed, reserveFeePercent ); // Since slices cannot be created when the loan is late, all interest collected can be assumed to split // pro-rata across the slices. So we scale the interest and principal to the slice ITranchedPool.ApplyResult memory applyResult = applyToSeniorTranche( poolSlices[i], scaleForSlice(poolSlices[i], interest, totalDeployed), scaleForSlice(poolSlices[i], principal, totalDeployed), juniorFeePercent, sliceInfo ); emitSharePriceUpdatedEvent(poolSlices[i].seniorTranche, applyResult); seniorApplyResult.interestRemaining = seniorApplyResult.interestRemaining.add(applyResult.interestRemaining); seniorApplyResult.principalRemaining = seniorApplyResult.principalRemaining.add(applyResult.principalRemaining); seniorApplyResult.reserveDeduction = seniorApplyResult.reserveDeduction.add(applyResult.reserveDeduction); } return seniorApplyResult; } function applyToAllJuniorTranches( ITranchedPool.PoolSlice[] storage poolSlices, uint256 interest, uint256 principal, uint256 reserveFeePercent, uint256 totalDeployed, IV2CreditLine creditLine ) public returns (uint256 totalReserveAmount) { for (uint256 i = 0; i < poolSlices.length; i++) { ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo( poolSlices[i], creditLine, totalDeployed, reserveFeePercent ); // Any remaining interest and principal is then shared pro-rata with the junior slices ITranchedPool.ApplyResult memory applyResult = applyToJuniorTranche( poolSlices[i], scaleForSlice(poolSlices[i], interest, totalDeployed), scaleForSlice(poolSlices[i], principal, totalDeployed), sliceInfo ); emitSharePriceUpdatedEvent(poolSlices[i].juniorTranche, applyResult); totalReserveAmount = totalReserveAmount.add(applyResult.reserveDeduction); } return totalReserveAmount; } function emitSharePriceUpdatedEvent( ITranchedPool.TrancheInfo memory tranche, ITranchedPool.ApplyResult memory applyResult ) internal { emit SharePriceUpdated( address(this), tranche.id, tranche.principalSharePrice, int256(tranche.principalSharePrice.sub(applyResult.oldPrincipalSharePrice)), tranche.interestSharePrice, int256(tranche.interestSharePrice.sub(applyResult.oldInterestSharePrice)) ); } function applyToSeniorTranche( ITranchedPool.PoolSlice storage slice, uint256 interestRemaining, uint256 principalRemaining, uint256 juniorFeePercent, ITranchedPool.SliceInfo memory sliceInfo ) public returns (ITranchedPool.ApplyResult memory) { // First determine the expected share price for the senior tranche. This is the gross amount the senior // tranche should receive. uint256 expectedInterestSharePrice = calculateExpectedSharePrice( slice.seniorTranche, sliceInfo.interestAccrued, slice ); uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice( slice.seniorTranche, sliceInfo.principalAccrued, slice ); // Deduct the junior fee and the protocol reserve uint256 desiredNetInterestSharePrice = scaleByFraction( expectedInterestSharePrice, ONE_HUNDRED.sub(juniorFeePercent.add(sliceInfo.reserveFeePercent)), ONE_HUNDRED ); // Collect protocol fee interest received (we've subtracted this from the senior portion above) uint256 reserveDeduction = scaleByFraction(interestRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED); interestRemaining = interestRemaining.sub(reserveDeduction); uint256 oldInterestSharePrice = slice.seniorTranche.interestSharePrice; uint256 oldPrincipalSharePrice = slice.seniorTranche.principalSharePrice; // Apply the interest remaining so we get up to the netInterestSharePrice (interestRemaining, principalRemaining) = applyBySharePrice( slice.seniorTranche, interestRemaining, principalRemaining, desiredNetInterestSharePrice, expectedPrincipalSharePrice ); return ITranchedPool.ApplyResult({ interestRemaining: interestRemaining, principalRemaining: principalRemaining, reserveDeduction: reserveDeduction, oldInterestSharePrice: oldInterestSharePrice, oldPrincipalSharePrice: oldPrincipalSharePrice }); } function applyToJuniorTranche( ITranchedPool.PoolSlice storage slice, uint256 interestRemaining, uint256 principalRemaining, ITranchedPool.SliceInfo memory sliceInfo ) public returns (ITranchedPool.ApplyResult memory) { // Then fill up the junior tranche with all the interest remaining, upto the principal share price uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add( usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited) ); uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice( slice.juniorTranche, sliceInfo.principalAccrued, slice ); uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice; uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice; (interestRemaining, principalRemaining) = applyBySharePrice( slice.juniorTranche, interestRemaining, principalRemaining, expectedInterestSharePrice, expectedPrincipalSharePrice ); // All remaining interest and principal is applied towards the junior tranche as interest interestRemaining = interestRemaining.add(principalRemaining); // Since any principal remaining is treated as interest (there is "extra" interest to be distributed) // we need to make sure to collect the protocol fee on the additional interest (we only deducted the // fee on the original interest portion) uint256 reserveDeduction = scaleByFraction(principalRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED); interestRemaining = interestRemaining.sub(reserveDeduction); principalRemaining = 0; (interestRemaining, principalRemaining) = applyByAmount( slice.juniorTranche, interestRemaining.add(principalRemaining), 0, interestRemaining.add(principalRemaining), 0 ); return ITranchedPool.ApplyResult({ interestRemaining: interestRemaining, principalRemaining: principalRemaining, reserveDeduction: reserveDeduction, oldInterestSharePrice: oldInterestSharePrice, oldPrincipalSharePrice: oldPrincipalSharePrice }); } function applyBySharePrice( ITranchedPool.TrancheInfo storage tranche, uint256 interestRemaining, uint256 principalRemaining, uint256 desiredInterestSharePrice, uint256 desiredPrincipalSharePrice ) public returns (uint256, uint256) { uint256 desiredInterestAmount = desiredAmountFromSharePrice( desiredInterestSharePrice, tranche.interestSharePrice, tranche.principalDeposited ); uint256 desiredPrincipalAmount = desiredAmountFromSharePrice( desiredPrincipalSharePrice, tranche.principalSharePrice, tranche.principalDeposited ); return applyByAmount(tranche, interestRemaining, principalRemaining, desiredInterestAmount, desiredPrincipalAmount); } function applyByAmount( ITranchedPool.TrancheInfo storage tranche, uint256 interestRemaining, uint256 principalRemaining, uint256 desiredInterestAmount, uint256 desiredPrincipalAmount ) public returns (uint256, uint256) { uint256 totalShares = tranche.principalDeposited; uint256 newSharePrice; (interestRemaining, newSharePrice) = applyToSharePrice( interestRemaining, tranche.interestSharePrice, desiredInterestAmount, totalShares ); tranche.interestSharePrice = newSharePrice; (principalRemaining, newSharePrice) = applyToSharePrice( principalRemaining, tranche.principalSharePrice, desiredPrincipalAmount, totalShares ); tranche.principalSharePrice = newSharePrice; return (interestRemaining, principalRemaining); } function migrateAccountingVariables(address originalClAddr, address newClAddr) public { IV2CreditLine originalCl = IV2CreditLine(originalClAddr); IV2CreditLine newCl = IV2CreditLine(newClAddr); // Copy over all accounting variables newCl.setBalance(originalCl.balance()); newCl.setLimit(originalCl.limit()); newCl.setInterestOwed(originalCl.interestOwed()); newCl.setPrincipalOwed(originalCl.principalOwed()); newCl.setTermEndTime(originalCl.termEndTime()); newCl.setNextDueTime(originalCl.nextDueTime()); newCl.setInterestAccruedAsOf(originalCl.interestAccruedAsOf()); newCl.setLastFullPaymentTime(originalCl.lastFullPaymentTime()); newCl.setTotalInterestAccrued(originalCl.totalInterestAccrued()); } function closeCreditLine(address originalCl) public { // Close out old CL IV2CreditLine oldCreditLine = IV2CreditLine(originalCl); oldCreditLine.setBalance(0); oldCreditLine.setLimit(0); oldCreditLine.setMaxLimit(0); } function desiredAmountFromSharePrice( uint256 desiredSharePrice, uint256 actualSharePrice, uint256 totalShares ) public pure returns (uint256) { // If the desired share price is lower, then ignore it, and leave it unchanged if (desiredSharePrice < actualSharePrice) { desiredSharePrice = actualSharePrice; } uint256 sharePriceDifference = desiredSharePrice.sub(actualSharePrice); return sharePriceToUsdc(sharePriceDifference, totalShares); } function applyToSharePrice( uint256 amountRemaining, uint256 currentSharePrice, uint256 desiredAmount, uint256 totalShares ) public pure returns (uint256, uint256) { // If no money left to apply, or don't need any changes, return the original amounts if (amountRemaining == 0 || desiredAmount == 0) { return (amountRemaining, currentSharePrice); } if (amountRemaining < desiredAmount) { // We don't have enough money to adjust share price to the desired level. So just use whatever amount is left desiredAmount = amountRemaining; } uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares); return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference)); } function scaleByPercentOwnership( ITranchedPool.TrancheInfo memory tranche, uint256 amount, ITranchedPool.PoolSlice memory slice ) public pure returns (uint256) { uint256 totalDeposited = slice.juniorTranche.principalDeposited.add(slice.seniorTranche.principalDeposited); return scaleByFraction(amount, tranche.principalDeposited, totalDeposited); } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol. pragma solidity 0.6.12; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/IMerkleDirectDistributor.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; contract MerkleDirectDistributor is IMerkleDirectDistributor, BaseUpgradeablePausable { using SafeERC20 for IERC20withDec; address public override gfi; bytes32 public override merkleRoot; // @dev This is a packed array of booleans. mapping(uint256 => uint256) private acceptedBitMap; function initialize( address owner, address _gfi, bytes32 _merkleRoot ) public initializer { require(owner != address(0), "Owner address cannot be empty"); require(_gfi != address(0), "GFI address cannot be empty"); require(_merkleRoot != 0, "Invalid Merkle root"); __BaseUpgradeablePausable__init(owner); gfi = _gfi; merkleRoot = _merkleRoot; } function isGrantAccepted(uint256 index) public view override returns (bool) { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; uint256 acceptedWord = acceptedBitMap[acceptedWordIndex]; uint256 mask = (1 << acceptedBitIndex); return acceptedWord & mask == mask; } function _setGrantAccepted(uint256 index) private { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex); } function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external override whenNotPaused { require(!isGrantAccepted(index), "Grant already accepted"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it accepted and perform the granting. _setGrantAccepted(index); IERC20withDec(gfi).safeTransfer(msg.sender, amount); emit GrantAccepted(index, msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol. pragma solidity 0.6.12; /// @notice Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this /// contract's Merkle root. interface IMerkleDirectDistributor { /// @notice Returns the address of the GFI contract that is the token distributed as rewards by /// this contract. function gfi() external view returns (address); /// @notice Returns the merkle root of the merkle tree containing grant details available to accept. function merkleRoot() external view returns (bytes32); /// @notice Returns true if the index has been marked accepted. function isGrantAccepted(uint256 index) external view returns (bool); /// @notice Causes the sender to accept the grant consisting of the given details. Reverts if /// the inputs (which includes who the sender is) are invalid. function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external; /// @notice This event is triggered whenever a call to #acceptGrant succeeds. event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Pool.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../protocol/core/CreditLine.sol"; contract TestCreditLine is CreditLine {} // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Accountant.sol"; import "../protocol/core/CreditLine.sol"; contract TestAccountant { function calculateInterestAndPrincipalAccrued( address creditLineAddress, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { CreditLine cl = CreditLine(creditLineAddress); return Accountant.calculateInterestAndPrincipalAccrued(cl, timestamp, lateFeeGracePeriod); } function calculateWritedownFor( address creditLineAddress, uint256 blockNumber, uint256 gracePeriod, uint256 maxLatePeriods ) public view returns (uint256, uint256) { CreditLine cl = CreditLine(creditLineAddress); return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods); } function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) { CreditLine cl = CreditLine(creditLineAddress); return Accountant.calculateAmountOwedForOneDay(cl); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/IPoolTokens.sol"; import "./Accountant.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; /** * @title Goldfinch's SeniorPool contract * @notice Main entry point for senior LPs (a.k.a. capital providers) * Automatically invests across borrower pools using an adjustable strategy. * @author Goldfinch */ contract SeniorPool is BaseUpgradeablePausable, ISeniorPool { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; uint256 public compoundBalance; mapping(ITranchedPool => uint256) public writedowns; event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares); event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount); event InterestCollected(address indexed payer, uint256 amount); event PrincipalCollected(address indexed payer, uint256 amount); event ReserveFundsCollected(address indexed user, uint256 amount); event PrincipalWrittenDown(address indexed tranchedPool, int256 amount); event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount); event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount); event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; // Initialize sharePrice to be identical to the legacy pool. This is in the initializer // because it must only ever happen once. sharePrice = config.getPool().sharePrice(); totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding(); totalWritedowns = config.getCreditDesk().totalWritedowns(); IERC20withDec usdc = config.getUSDC(); // Sanity check the address usdc.totalSupply(); bool success = usdc.approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the * equivalent value of FIDU tokens * @param amount The amount of USDC to deposit */ function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(amount > 0, "Must deposit more than zero"); // Check if the amount of new shares to be added is within limits depositShares = getNumShares(amount); uint256 potentialNewTotalShares = totalShares().add(depositShares); require(sharesWithinLimit(potentialNewTotalShares), "Deposit would put the senior pool over the total limit."); emit DepositMade(msg.sender, amount, depositShares); bool success = doUSDCTransfer(msg.sender, address(this), amount); require(success, "Failed to transfer for deposit"); config.getFidu().mintTo(msg.sender, depositShares); return depositShares; } /** * @notice Identical to deposit, except it allows for a passed up signature to permit * the Senior Pool to move funds on behalf of the user, all within one transaction. * @param amount The amount of USDC to deposit * @param v secp256k1 signature component * @param r secp256k1 signature component * @param s secp256k1 signature component */ function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 depositShares) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(amount); } /** * @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens * @param usdcAmount The amount of USDC to withdraw */ function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(usdcAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 withdrawShares = getNumShares(usdcAmount); return _withdraw(usdcAmount, withdrawShares); } /** * @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender * @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares */ function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(fiduAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount); uint256 withdrawShares = fiduAmount; return _withdraw(usdcAmount, withdrawShares); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } /** * @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally. * This is done to earn interest on latent funds until we have other borrowers who can use it. * * Requirements: * - The caller must be an admin. */ function sweepToCompound() public override onlyAdmin whenNotPaused { IERC20 usdc = config.getUSDC(); uint256 usdcBalance = usdc.balanceOf(address(this)); ICUSDCContract cUSDC = config.getCUSDCContract(); // Approve compound to the exact amount bool success = usdc.approve(address(cUSDC), usdcBalance); require(success, "Failed to approve USDC for compound"); sweepToCompound(cUSDC, usdcBalance); // Remove compound approval to be extra safe success = config.getUSDC().approve(address(cUSDC), 0); require(success, "Failed to approve USDC for compound"); } /** * @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned. * This is done automatically on drawdown or withdraw, but can be called manually if necessary. * * Requirements: * - The caller must be an admin. */ function sweepFromCompound() public override onlyAdmin whenNotPaused { _sweepFromCompound(); } /** * @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy * @param pool An ITranchedPool whose senior tranche should be considered for investment */ function invest(ITranchedPool pool) public override whenNotPaused nonReentrant { require(validPool(pool), "Pool must be valid"); if (compoundBalance > 0) { _sweepFromCompound(); } ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); uint256 amount = strategy.invest(this, pool); require(amount > 0, "Investment amount must be positive"); approvePool(pool, amount); pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount); emit InvestmentMadeInSenior(address(pool), amount); totalLoansOutstanding = totalLoansOutstanding.add(amount); } function estimateInvestment(ITranchedPool pool) public view override returns (uint256) { require(validPool(pool), "Pool must be valid"); ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); return strategy.estimateInvestment(this, pool); } /** * @notice Redeem interest and/or principal from an ITranchedPool investment * @param tokenId the ID of an IPoolTokens token to be redeemed */ function redeem(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId); _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed); } /** * @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price * down if we're considering the investment a loss, or up if the borrower has subsequently * made repayments that restore confidence that the full loan will be repaid. * @param tokenId the ID of an IPoolTokens token to be considered for writedown */ function writedown(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down"); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); require(validPool(pool), "Pool must be valid"); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); uint256 prevWritedownAmount = writedowns[pool]; if (writedownPercent == 0 && prevWritedownAmount == 0) { return; } int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount); writedowns[pool] = writedownAmount; distributeLosses(writedownDelta); if (writedownDelta > 0) { // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns. totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); } else { totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } emit PrincipalWrittenDown(address(pool), writedownDelta); } /** * @notice Calculates the writedown amount for a particular pool position * @param tokenId The token reprsenting the position * @return The amount in dollars the principal should be written down by */ function calculateWritedown(uint256 tokenId) public view override returns (uint256) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); return writedownAmount; } /** * @notice Returns the net assests controlled by and owed to the pool */ function assets() public view override returns (uint256) { return compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns); } /** * @notice Converts and USDC amount to FIDU amount * @param amount USDC amount to convert to FIDU */ function getNumShares(uint256 amount) public view override returns (uint256) { return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice); } /* Internal Functions */ function _calculateWritedown(ITranchedPool pool, uint256 principal) internal view returns (uint256 writedownPercent, uint256 writedownAmount) { return Accountant.calculateWritedownForPrincipal( pool.creditLine(), principal, currentTime(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function distributeLosses(int256 writedownDelta) internal { if (writedownDelta > 0) { uint256 delta = usdcToSharePrice(uint256(writedownDelta)); sharePrice = sharePrice.add(delta); } else { // If delta is negative, convert to positive uint, and sub from sharePrice uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1)); sharePrice = sharePrice.sub(delta); } } function fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function usdcToFidu(uint256 amount) internal pure returns (uint256) { return amount.mul(fiduMantissa()).div(usdcMantissa()); } function fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(fiduMantissa().div(usdcMantissa())); } function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) { return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa())); } function sharesWithinLimit(uint256 _totalShares) internal view returns (bool) { return _totalShares.mul(sharePrice).div(fiduMantissa()) <= usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit))); } function doUSDCTransfer( address from, address to, uint256 amount ) internal returns (bool) { require(to != address(0), "Can't send to zero address"); IERC20withDec usdc = config.getUSDC(); return usdc.transferFrom(from, to, amount); } function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) { IFidu fidu = config.getFidu(); // Determine current shares the address has and the shares requested to withdraw uint256 currentShares = fidu.balanceOf(msg.sender); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator()); userAmount = usdcAmount.sub(reserveAmount); emit WithdrawalMade(msg.sender, userAmount, reserveAmount); // Send the amounts bool success = doUSDCTransfer(address(this), msg.sender, userAmount); require(success, "Failed to transfer for withdraw"); sendToReserve(reserveAmount, msg.sender); // Burn the shares fidu.burnFrom(msg.sender, withdrawShares); return userAmount; } function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal { // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains // before we can add additional capital to Compound require(compoundBalance == 0, "Cannot sweep when we already have a compound balance"); require(usdcAmount != 0, "Amount to sweep cannot be zero"); uint256 error = cUSDC.mint(usdcAmount); require(error == 0, "Sweep to compound failed"); compoundBalance = usdcAmount; } function _sweepFromCompound() internal { ICUSDCContract cUSDC = config.getCUSDCContract(); sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this))); } function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal { uint256 cBalance = compoundBalance; require(cBalance != 0, "No funds on compound"); require(cUSDCAmount != 0, "Amount to sweep cannot be zero"); IERC20 usdc = config.getUSDC(); uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this)); uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent(); uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount); uint256 error = cUSDC.redeem(cUSDCAmount); uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this)); require(error == 0, "Sweep from compound failed"); require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount"); uint256 interestAccrued = redeemedUSDC.sub(cBalance); uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator()); uint256 poolAmount = interestAccrued.sub(reserveAmount); _collectInterestAndPrincipal(address(this), poolAmount, 0); if (reserveAmount > 0) { sendToReserve(reserveAmount, address(cUSDC)); } compoundBalance = 0; } function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) { // See https://compound.finance/docs#protocol-math // But note, the docs and reality do not agree. Docs imply that that exchange rate is // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16 // 1e16 is also what Sheraz at Certik said. uint256 usdcDecimals = 6; uint256 cUSDCDecimals = 8; // We multiply in the following order, for the following reasons... // Amount in cToken (1e8) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are) // Downscale to cToken decimals (1e8) // Downscale from cToken to USDC decimals (8 to 6) return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2); } function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal { uint256 increment = usdcToSharePrice(interest); sharePrice = sharePrice.add(increment); if (interest > 0) { emit InterestCollected(from, interest); } if (principal > 0) { emit PrincipalCollected(from, principal); totalLoansOutstanding = totalLoansOutstanding.sub(principal); } } function sendToReserve(uint256 amount, address userForEvent) internal { emit ReserveFundsCollected(userForEvent, amount); bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount); require(success, "Reserve transfer was not successful"); } function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) { return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares()); } function totalShares() internal view returns (uint256) { return config.getFidu().totalSupply(); } function validPool(ITranchedPool pool) internal view returns (bool) { return config.getPoolTokens().validPool(address(pool)); } function approvePool(ITranchedPool pool, uint256 allowance) internal { IERC20withDec usdc = config.getUSDC(); bool success = usdc.approve(address(pool), allowance); require(success, "Failed to approve USDC"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/SeniorPool.sol"; contract TestSeniorPool is SeniorPool { function _getNumShares(uint256 amount) public view returns (uint256) { return getNumShares(amount); } function _usdcMantissa() public pure returns (uint256) { return usdcMantissa(); } function _fiduMantissa() public pure returns (uint256) { return fiduMantissa(); } function _usdcToFidu(uint256 amount) public pure returns (uint256) { return usdcToFidu(amount); } function _setSharePrice(uint256 newSharePrice) public returns (uint256) { sharePrice = newSharePrice; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ICommunityRewards.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../library/CommunityRewardsVesting.sol"; contract CommunityRewards is ICommunityRewards, ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using ConfigHelper for GoldfinchConfig; using CommunityRewardsVesting for CommunityRewardsVesting.Rewards; /* ========== EVENTS ========== */ event GoldfinchConfigUpdated(address indexed who, address configAddress); /* ========== STATE VARIABLES ========== */ bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE"); GoldfinchConfig public config; /// @notice Total rewards available for granting, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice Token launch time in seconds. This is used in vesting. uint256 public tokenLaunchTimeInSeconds; /// @dev NFT tokenId => rewards grant mapping(uint256 => CommunityRewardsVesting.Rewards) public grants; // solhint-disable-next-line func-name-mixedcase function __initialize__( address owner, GoldfinchConfig _config, uint256 _tokenLaunchTimeInSeconds ) external initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 Community Rewards Tokens", "GFI-V2-CR"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setupRole(DISTRIBUTOR_ROLE, owner); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(DISTRIBUTOR_ROLE, OWNER_ROLE); tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds; config = _config; } /* ========== VIEWS ========== */ /// @notice The token being disbursed as rewards function rewardsToken() public view override returns (IERC20withDec) { return config.getGFI(); } /// @notice Returns the rewards claimable by a given grant token, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view override returns (uint256 rewards) { return grants[tokenId].claimable(); } /// @notice Returns the rewards that will have vested for some grant with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 granted, uint256 cliffLength, uint256 vestingInterval, uint256 revokedAt, uint256 time ) external pure override returns (uint256 rewards) { return CommunityRewardsVesting.getTotalVestedAt(start, end, granted, cliffLength, vestingInterval, revokedAt, time); } /* ========== MUTATIVE, ADMIN-ONLY FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) external override onlyAdmin { require(rewards > 0, "Cannot load 0 rewards"); rewardsAvailable = rewardsAvailable.add(rewards); rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); emit RewardAdded(rewards); } /// @notice Revokes rewards that have not yet vested, for a grant. The unvested rewards are /// now considered available for allocation in another grant. /// @param tokenId The tokenId corresponding to the grant whose unvested rewards to revoke. function revokeGrant(uint256 tokenId) external override whenNotPaused onlyAdmin { CommunityRewardsVesting.Rewards storage grant = grants[tokenId]; require(grant.totalGranted > 0, "Grant not defined for token id"); require(grant.revokedAt == 0, "Grant has already been revoked"); uint256 totalUnvested = grant.totalUnvestedAt(block.timestamp); require(totalUnvested > 0, "Grant has fully vested"); rewardsAvailable = rewardsAvailable.add(totalUnvested); grant.revokedAt = block.timestamp; emit GrantRevoked(tokenId, totalUnvested); } function setTokenLaunchTimeInSeconds(uint256 _tokenLaunchTimeInSeconds) external onlyAdmin { tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds; } /// @notice updates current config function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ========== MUTATIVE, NON-ADMIN-ONLY FUNCTIONS ========== */ /// @notice Grant rewards to a recipient. The recipient address receives an /// an NFT representing their rewards grant. They can present the NFT to `getReward()` /// to claim their rewards. Rewards vest over a schedule. /// @param recipient The recipient of the grant. /// @param amount The amount of `rewardsToken()` to grant. /// @param vestingLength The duration (in seconds) over which the grant vests. /// @param cliffLength The duration (in seconds) from the start of the grant, before which has elapsed /// the vested amount remains 0. /// @param vestingInterval The interval (in seconds) at which vesting occurs. Must be a factor of `vestingLength`. function grant( address recipient, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ) external override nonReentrant whenNotPaused onlyDistributor returns (uint256 tokenId) { return _grant(recipient, amount, vestingLength, cliffLength, vestingInterval); } function _grant( address recipient, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ) internal returns (uint256 tokenId) { require(amount > 0, "Cannot grant 0 amount"); require(cliffLength <= vestingLength, "Cliff length cannot exceed vesting length"); require(vestingLength.mod(vestingInterval) == 0, "Vesting interval must be a factor of vesting length"); require(amount <= rewardsAvailable, "Cannot grant amount due to insufficient funds"); rewardsAvailable = rewardsAvailable.sub(amount); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); grants[tokenId] = CommunityRewardsVesting.Rewards({ totalGranted: amount, totalClaimed: 0, startTime: tokenLaunchTimeInSeconds, endTime: tokenLaunchTimeInSeconds.add(vestingLength), cliffLength: cliffLength, vestingInterval: vestingInterval, revokedAt: 0 }); _mint(recipient, tokenId); emit Granted(recipient, tokenId, amount, vestingLength, cliffLength, vestingInterval); return tokenId; } /// @notice Claim rewards for a given grant /// @param tokenId A grant token ID function getReward(uint256 tokenId) external override nonReentrant whenNotPaused { require(ownerOf(tokenId) == msg.sender, "access denied"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { grants[tokenId].claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /* ========== MODIFIERS ========== */ function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } function isDistributor() public view returns (bool) { return hasRole(DISTRIBUTOR_ROLE, _msgSender()); } modifier onlyDistributor() { require(isDistributor(), "Must have distributor role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; import "../interfaces/IERC20withDec.sol"; interface ICommunityRewards is IERC721 { function rewardsToken() external view returns (IERC20withDec); function claimableRewards(uint256 tokenId) external view returns (uint256 rewards); function totalVestedAt( uint256 start, uint256 end, uint256 granted, uint256 cliffLength, uint256 vestingInterval, uint256 revokedAt, uint256 time ) external pure returns (uint256 rewards); function grant( address recipient, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ) external returns (uint256 tokenId); function loadRewards(uint256 rewards) external; function revokeGrant(uint256 tokenId) external; function getReward(uint256 tokenId) external; event RewardAdded(uint256 reward); event Granted( address indexed user, uint256 indexed tokenId, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ); event GrantRevoked(uint256 indexed tokenId, uint256 totalUnvested); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; library CommunityRewardsVesting { using SafeMath for uint256; using CommunityRewardsVesting for Rewards; /// @dev All time values in the Rewards struct (i.e. `startTime`, `endTime`, /// `cliffLength`, `vestingInterval`, `revokedAt`) use the same units: seconds. All timestamp /// values (i.e. `startTime`, `endTime`, `revokedAt`) are seconds since the unix epoch. /// @dev `cliffLength` is the duration from the start of the grant, before which has elapsed /// the vested amount remains 0. /// @dev `vestingInterval` is the interval at which vesting occurs. For rewards to have /// vested fully only at `endTime`, `vestingInterval` must be a factor of /// `endTime.sub(startTime)`. If `vestingInterval` is not thusly a factor, the calculation /// of `totalVestedAt()` would calculate rewards to have fully vested as of the time of the /// last whole `vestingInterval`'s elapsing before `endTime`. struct Rewards { uint256 totalGranted; uint256 totalClaimed; uint256 startTime; uint256 endTime; uint256 cliffLength; uint256 vestingInterval; uint256 revokedAt; } function claim(Rewards storage rewards, uint256 reward) internal { rewards.totalClaimed = rewards.totalClaimed.add(reward); } function claimable(Rewards storage rewards) internal view returns (uint256) { return claimable(rewards, block.timestamp); } function claimable(Rewards storage rewards, uint256 time) internal view returns (uint256) { return rewards.totalVestedAt(time).sub(rewards.totalClaimed); } function totalUnvestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) { return rewards.totalGranted.sub(rewards.totalVestedAt(time)); } function totalVestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) { return getTotalVestedAt( rewards.startTime, rewards.endTime, rewards.totalGranted, rewards.cliffLength, rewards.vestingInterval, rewards.revokedAt, time ); } function getTotalVestedAt( uint256 start, uint256 end, uint256 granted, uint256 cliffLength, uint256 vestingInterval, uint256 revokedAt, uint256 time ) internal pure returns (uint256) { if (time < start.add(cliffLength)) { return 0; } if (end <= start) { return granted; } uint256 elapsedVestingTimestamp = revokedAt > 0 ? Math.min(revokedAt, time) : time; uint256 elapsedVestingUnits = (elapsedVestingTimestamp.sub(start)).div(vestingInterval); uint256 totalVestingUnits = (end.sub(start)).div(vestingInterval); return Math.min(granted.mul(elapsedVestingUnits).div(totalVestingUnits), granted); } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol. pragma solidity 0.6.12; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/ICommunityRewards.sol"; import "../interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor { address public immutable override communityRewards; bytes32 public immutable override merkleRoot; // @dev This is a packed array of booleans. mapping(uint256 => uint256) private acceptedBitMap; constructor(address communityRewards_, bytes32 merkleRoot_) public { require(communityRewards_ != address(0), "Cannot use the null address"); require(merkleRoot_ != 0, "Invalid merkle root provided"); communityRewards = communityRewards_; merkleRoot = merkleRoot_; } function isGrantAccepted(uint256 index) public view override returns (bool) { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; uint256 acceptedWord = acceptedBitMap[acceptedWordIndex]; uint256 mask = (1 << acceptedBitIndex); return acceptedWord & mask == mask; } function _setGrantAccepted(uint256 index) private { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex); } function acceptGrant( uint256 index, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval, bytes32[] calldata merkleProof ) external override { require(!isGrantAccepted(index), "Grant already accepted"); // Verify the merkle proof. // /// @dev Per the Warning in /// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#non-standard-packed-mode, /// it is important that no more than one of the arguments to `abi.encodePacked()` here be a /// dynamic type (see definition in /// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#formal-specification-of-the-encoding). bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount, vestingLength, cliffLength, vestingInterval)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it accepted and perform the granting. _setGrantAccepted(index); uint256 tokenId = ICommunityRewards(communityRewards).grant( msg.sender, amount, vestingLength, cliffLength, vestingInterval ); emit GrantAccepted(tokenId, index, msg.sender, amount, vestingLength, cliffLength, vestingInterval); } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol. pragma solidity 0.6.12; /// @notice Enables the granting of a CommunityRewards grant, if the grant details exist in this /// contract's Merkle root. interface IMerkleDistributor { /// @notice Returns the address of the CommunityRewards contract whose grants are distributed by this contract. function communityRewards() external view returns (address); /// @notice Returns the merkle root of the merkle tree containing grant details available to accept. function merkleRoot() external view returns (bytes32); /// @notice Returns true if the index has been marked accepted. function isGrantAccepted(uint256 index) external view returns (bool); /// @notice Causes the sender to accept the grant consisting of the given details. Reverts if /// the inputs (which includes who the sender is) are invalid. function acceptGrant( uint256 index, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval, bytes32[] calldata merkleProof ) external; /// @notice This event is triggered whenever a call to #acceptGrant succeeds. event GrantAccepted( uint256 indexed tokenId, uint256 indexed index, address indexed account, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../core/BaseUpgradeablePausable.sol"; import "../core/ConfigHelper.sol"; import "../core/CreditLine.sol"; import "../core/GoldfinchConfig.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IBorrower.sol"; import "@opengsn/gsn/contracts/BaseRelayRecipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Goldfinch's Borrower contract * @notice These contracts represent the a convenient way for a borrower to interact with Goldfinch * They are 100% optional. However, they let us add many sophisticated and convient features for borrowers * while still keeping our core protocol small and secure. We therefore expect most borrowers will use them. * This contract is the "official" borrower contract that will be maintained by Goldfinch governance. However, * in theory, anyone can fork or create their own version, or not use any contract at all. The core functionality * is completely agnostic to whether it is interacting with a contract or an externally owned account (EOA). * @author Goldfinch */ contract Borrower is BaseUpgradeablePausable, BaseRelayRecipient, IBorrower { using SafeMath for uint256; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; address private constant USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); address private constant BUSD_ADDRESS = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53); address private constant GUSD_ADDRESS = address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd); address private constant DAI_ADDRESS = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); function initialize(address owner, address _config) external override initializer { require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); trustedForwarder = config.trustedForwarderAddress(); // Handle default approvals. Pool, and OneInch for maximum amounts address oneInch = config.oneInchAddress(); IERC20withDec usdc = config.getUSDC(); usdc.approve(oneInch, uint256(-1)); bytes memory data = abi.encodeWithSignature("approve(address,uint256)", oneInch, uint256(-1)); invoke(USDT_ADDRESS, data); invoke(BUSD_ADDRESS, data); invoke(GUSD_ADDRESS, data); invoke(DAI_ADDRESS, data); } function lockJuniorCapital(address poolAddress) external onlyAdmin { ITranchedPool(poolAddress).lockJuniorCapital(); } function lockPool(address poolAddress) external onlyAdmin { ITranchedPool(poolAddress).lockPool(); } /** * @notice Allows a borrower to drawdown on their creditline through the CreditDesk. * @param poolAddress The creditline from which they would like to drawdown * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown * @param addressToSendTo The address where they would like the funds sent. If the zero address is passed, * it will be defaulted to the contracts address (msg.sender). This is a convenience feature for when they would * like the funds sent to an exchange or alternate wallet, different from the authentication address */ function drawdown( address poolAddress, uint256 amount, address addressToSendTo ) external onlyAdmin { ITranchedPool(poolAddress).drawdown(amount); if (addressToSendTo == address(0) || addressToSendTo == address(this)) { addressToSendTo = _msgSender(); } transferERC20(config.usdcAddress(), addressToSendTo, amount); } function drawdownWithSwapOnOneInch( address poolAddress, uint256 amount, address addressToSendTo, address toToken, uint256 minTargetAmount, uint256[] calldata exchangeDistribution ) public onlyAdmin { // Drawdown to the Borrower contract ITranchedPool(poolAddress).drawdown(amount); // Do the swap swapOnOneInch(config.usdcAddress(), toToken, amount, minTargetAmount, exchangeDistribution); // Default to sending to the owner, and don't let funds stay in this contract if (addressToSendTo == address(0) || addressToSendTo == address(this)) { addressToSendTo = _msgSender(); } // Fulfill the send to bytes memory _data = abi.encodeWithSignature("balanceOf(address)", address(this)); uint256 receivedAmount = toUint256(invoke(toToken, _data)); transferERC20(toToken, addressToSendTo, receivedAmount); } function transferERC20( address token, address to, uint256 amount ) public onlyAdmin { bytes memory _data = abi.encodeWithSignature("transfer(address,uint256)", to, amount); invoke(token, _data); } /** * @notice Allows a borrower to payback loans by calling the `pay` function directly on the CreditDesk * @param poolAddress The credit line to be paid back * @param amount The amount, in USDC atomic units, that the borrower wishes to pay */ function pay(address poolAddress, uint256 amount) external onlyAdmin { IERC20withDec usdc = config.getUSDC(); bool success = usdc.transferFrom(_msgSender(), address(this), amount); require(success, "Failed to transfer USDC"); _transferAndPay(usdc, poolAddress, amount); } function payMultiple(address[] calldata pools, uint256[] calldata amounts) external onlyAdmin { require(pools.length == amounts.length, "Pools and amounts must be the same length"); uint256 totalAmount; for (uint256 i = 0; i < amounts.length; i++) { totalAmount = totalAmount.add(amounts[i]); } IERC20withDec usdc = config.getUSDC(); // Do a single transfer, which is cheaper bool success = usdc.transferFrom(_msgSender(), address(this), totalAmount); require(success, "Failed to transfer USDC"); for (uint256 i = 0; i < amounts.length; i++) { _transferAndPay(usdc, pools[i], amounts[i]); } } function payInFull(address poolAddress, uint256 amount) external onlyAdmin { IERC20withDec usdc = config.getUSDC(); bool success = usdc.transferFrom(_msgSender(), address(this), amount); require(success, "Failed to transfer USDC"); _transferAndPay(usdc, poolAddress, amount); require(ITranchedPool(poolAddress).creditLine().balance() == 0, "Failed to fully pay off creditline"); } function payWithSwapOnOneInch( address poolAddress, uint256 originAmount, address fromToken, uint256 minTargetAmount, uint256[] calldata exchangeDistribution ) external onlyAdmin { transferFrom(fromToken, _msgSender(), address(this), originAmount); IERC20withDec usdc = config.getUSDC(); swapOnOneInch(fromToken, address(usdc), originAmount, minTargetAmount, exchangeDistribution); uint256 usdcBalance = usdc.balanceOf(address(this)); _transferAndPay(usdc, poolAddress, usdcBalance); } function payMultipleWithSwapOnOneInch( address[] calldata pools, uint256[] calldata minAmounts, uint256 originAmount, address fromToken, uint256[] calldata exchangeDistribution ) external onlyAdmin { require(pools.length == minAmounts.length, "Pools and amounts must be the same length"); uint256 totalMinAmount = 0; for (uint256 i = 0; i < minAmounts.length; i++) { totalMinAmount = totalMinAmount.add(minAmounts[i]); } transferFrom(fromToken, _msgSender(), address(this), originAmount); IERC20withDec usdc = config.getUSDC(); swapOnOneInch(fromToken, address(usdc), originAmount, totalMinAmount, exchangeDistribution); for (uint256 i = 0; i < minAmounts.length; i++) { _transferAndPay(usdc, pools[i], minAmounts[i]); } uint256 remainingUSDC = usdc.balanceOf(address(this)); if (remainingUSDC > 0) { _transferAndPay(usdc, pools[0], remainingUSDC); } } function _transferAndPay( IERC20withDec usdc, address poolAddress, uint256 amount ) internal { ITranchedPool pool = ITranchedPool(poolAddress); // We don't use transferFrom since it would require a separate approval per creditline bool success = usdc.transfer(address(pool.creditLine()), amount); require(success, "USDC Transfer to creditline failed"); pool.assess(); } function transferFrom( address erc20, address sender, address recipient, uint256 amount ) internal { bytes memory _data; // Do a low-level invoke on this transfer, since Tether fails if we use the normal IERC20 interface _data = abi.encodeWithSignature("transferFrom(address,address,uint256)", sender, recipient, amount); invoke(address(erc20), _data); } function swapOnOneInch( address fromToken, address toToken, uint256 originAmount, uint256 minTargetAmount, uint256[] calldata exchangeDistribution ) internal { bytes memory _data = abi.encodeWithSignature( "swap(address,address,uint256,uint256,uint256[],uint256)", fromToken, toToken, originAmount, minTargetAmount, exchangeDistribution, 0 ); invoke(config.oneInchAddress(), _data); } /** * @notice Performs a generic transaction. * @param _target The address for the transaction. * @param _data The data of the transaction. * Mostly copied from Argent: * https://github.com/argentlabs/argent-contracts/blob/develop/contracts/wallet/BaseWallet.sol#L111 */ function invoke(address _target, bytes memory _data) internal returns (bytes memory) { // External contracts can be compiled with different Solidity versions // which can cause "revert without reason" when called through, // for example, a standard IERC20 ABI compiled on the latest version. // This low-level call avoids that issue. bool success; bytes memory _res; // solhint-disable-next-line avoid-low-level-calls (success, _res) = _target.call(_data); if (!success && _res.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } else if (!success) { revert("VM: wallet invoke reverted"); } return _res; } function toUint256(bytes memory _bytes) internal pure returns (uint256 value) { assembly { value := mload(add(_bytes, 0x20)) } } // OpenZeppelin contracts come with support for GSN _msgSender() (which just defaults to msg.sender) // Since there are two different versions of the function in the hierarchy, we need to instruct solidity to // use the relay recipient version which can actually pull the real sender from the parameters. // https://www.notion.so/My-contract-is-using-OpenZeppelin-How-do-I-add-GSN-support-2bee7e9d5f774a0cbb60d3a8de03e9fb function _msgSender() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (address payable) { return BaseRelayRecipient._msgSender(); } function _msgData() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (bytes memory ret) { return BaseRelayRecipient._msgData(); } function versionRecipient() external view override returns (string memory) { return "2.0.0"; } } // SPDX-Licence-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBorrower { function initialize(address owner, address _config) external; } // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity ^0.6.2; import "./interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize(),20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr,32), size) calldatacopy(add(ptr,64), 0, size) return(ptr, add(size,64)) } } else { return msg.data; } } } // SPDX-License-Identifier:MIT pragma solidity ^0.6.2; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IBorrower.sol"; import "../../interfaces/ITranchedPool.sol"; import "./ConfigHelper.sol"; /** * @title GoldfinchFactory * @notice Contract that allows us to create other contracts, such as CreditLines and BorrowerContracts * Note GoldfinchFactory is a legacy name. More properly this can be considered simply the GoldfinchFactory * @author Goldfinch */ contract GoldfinchFactory is BaseUpgradeablePausable { GoldfinchConfig public config; /// Role to allow for pool creation bytes32 public constant BORROWER_ROLE = keccak256("BORROWER_ROLE"); using ConfigHelper for GoldfinchConfig; event BorrowerCreated(address indexed borrower, address indexed owner); event PoolCreated(address indexed pool, address indexed borrower); event GoldfinchConfigUpdated(address indexed who, address configAddress); event CreditLineCreated(address indexed creditLine); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; _performUpgrade(); } function performUpgrade() external onlyAdmin { _performUpgrade(); } function _performUpgrade() internal { if (getRoleAdmin(BORROWER_ROLE) != OWNER_ROLE) { _setRoleAdmin(BORROWER_ROLE, OWNER_ROLE); } } /** * @notice Allows anyone to create a CreditLine contract instance * @dev There is no value to calling this function directly. It is only meant to be called * by a TranchedPool during it's creation process. */ function createCreditLine() external returns (address) { address creditLine = deployMinimal(config.creditLineImplementationAddress()); emit CreditLineCreated(creditLine); return creditLine; } /** * @notice Allows anyone to create a Borrower contract instance * @param owner The address that will own the new Borrower instance */ function createBorrower(address owner) external returns (address) { address _borrower = deployMinimal(config.borrowerImplementationAddress()); IBorrower borrower = IBorrower(_borrower); borrower.initialize(owner, address(config)); emit BorrowerCreated(address(borrower), owner); return address(borrower); } /** * @notice Allows anyone to create a new TranchedPool for a single borrower * @param _borrower The borrower for whom the CreditLine will be created * @param _juniorFeePercent The percent of senior interest allocated to junior investors, expressed as * integer percents. eg. 20% is simply 20 * @param _limit The maximum amount a borrower can drawdown from this CreditLine * @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer. * We assume 18 digits of precision. For example, to submit 15.34%, you would pass up 153400000000000000, * and 5.34% would be 53400000000000000 * @param _paymentPeriodInDays How many days in each payment period. * ie. the frequency with which they need to make payments. * @param _termInDays Number of days in the credit term. It is used to set the `termEndTime` upon first drawdown. * ie. The credit line should be fully paid off {_termIndays} days after the first drawdown. * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your * normal rate is 15%, then you will pay 18% while you are late. Also expressed as an 18 decimal precision integer * * Requirements: * You are the admin */ function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) external onlyAdminOrBorrower returns (address pool) { address tranchedPoolImplAddress = config.tranchedPoolAddress(); pool = deployMinimal(tranchedPoolImplAddress); ITranchedPool(pool).initialize( address(config), _borrower, _juniorFeePercent, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays, _fundableAt, _allowedUIDTypes ); emit PoolCreated(pool, _borrower); config.getPoolTokens().onPoolCreated(pool); return pool; } function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) external onlyCreditDesk returns (address pool) { address tranchedPoolImplAddress = config.migratedTranchedPoolAddress(); pool = deployMinimal(tranchedPoolImplAddress); ITranchedPool(pool).initialize( address(config), _borrower, _juniorFeePercent, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays, _fundableAt, _allowedUIDTypes ); emit PoolCreated(pool, _borrower); config.getPoolTokens().onPoolCreated(pool); return pool; } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } // Stolen from: // https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/ProxyFactory.sol function deployMinimal(address _logic) internal returns (address proxy) { bytes20 targetBytes = bytes20(_logic); // solhint-disable-next-line no-inline-assembly assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } return proxy; } function isBorrower() public view returns (bool) { return hasRole(BORROWER_ROLE, _msgSender()); } modifier onlyAdminOrBorrower() { require(isAdmin() || isBorrower(), "Must have admin or borrower role to perform this action"); _; } modifier onlyCreditDesk() { require(msg.sender == config.creditDeskAddress(), "Only the CreditDesk can call this"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "../library/SafeERC20Transfer.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../interfaces/IPoolTokens.sol"; import "../interfaces/ITranchedPool.sol"; import "../interfaces/IBackerRewards.sol"; // Basically, Every time a interest payment comes back // we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit // Every dollar of interest received from 0->maxInterestDollarsEligible // has a allocated amount of rewards based on a sqrt function. // When a interest payment comes in for a given Pool or the pool balance increases // we recalculate the pool's accRewardsPerPrincipalDollar // equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`: // (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply) // When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar // Every time a PoolToken withdraws rewards, we determine the allocated rewards, // increase that PoolToken's rewardsClaimed, and transfer the owner the gfi contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, SafeERC20Transfer { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; struct BackerRewardsInfo { uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar } struct BackerRewardsTokenInfo { uint256 rewardsClaimed; // gfi claimed uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint() } uint256 public totalRewards; // total amount of GFI rewards available, times 1e18 uint256 public maxInterestDollarsEligible; // interest $ eligible for gfi rewards, times 1e18 uint256 public totalInterestReceived; // counter of total interest repayments, times 1e6 uint256 public totalRewardPercentOfTotalGFI; // totalRewards/totalGFISupply, times 1e18 mapping(uint256 => BackerRewardsTokenInfo) public tokens; // poolTokenId -> BackerRewardsTokenInfo mapping(address => BackerRewardsInfo) public pools; // pool.address -> BackerRewardsInfo // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } /** * @notice Calculates the accRewardsPerPrincipalDollar for a given pool, when a interest payment is received by the protocol * @param _interestPaymentAmount The amount of total dollars the interest payment, expects 10^6 value */ function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool { // note: do not use a require statment because that will TranchedPool kill execution if (_interestPaymentAmount > 0) { _allocateRewards(_interestPaymentAmount); } } /** * @notice Set the total gfi rewards and the % of total GFI * @param _totalRewards The amount of GFI rewards available, expects 10^18 value */ function setTotalRewards(uint256 _totalRewards) public onlyAdmin { totalRewards = _totalRewards; uint256 totalGFISupply = config.getGFI().totalSupply(); totalRewardPercentOfTotalGFI = _totalRewards.mul(mantissa()).div(totalGFISupply).mul(100); emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI); } /** * @notice Set the total interest received to date. This should only be called once on contract deploy. * @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value */ function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin { totalInterestReceived = _totalInterestReceived; emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived); } /** * @notice Set the max dollars across the entire protocol that are eligible for GFI rewards * @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value */ function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin { maxInterestDollarsEligible = _maxInterestDollarsEligible; emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible); } /** * @notice When a pool token is minted for multiple drawdowns, set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price * @param tokenId Pool token id */ function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external override { require(_msgSender() == config.poolTokensAddress(), "Invalid sender!"); require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!"); if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) { return; } IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address"); tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool].accRewardsPerPrincipalDollar; } /** * @notice Calculate the gross available gfi rewards for a PoolToken * @param tokenId Pool token id * @return The amount of GFI claimable */ function poolTokenClaimableRewards(uint256 tokenId) public view returns (uint256) { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); // Note: If a TranchedPool is oversubscribed, reward allocation's scale down proportionately. uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool].accRewardsPerPrincipalDollar.sub( tokens[tokenId].accRewardsPerPrincipalDollarAtMint ); uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(mantissa()); /* equation for token claimable rewards: token.principalAmount * (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint) - token.rewardsClaimed */ return usdcToAtomic(tokenInfo.principalAmount).mul(diffOfAccRewardsPerPrincipalDollar).sub(rewardsClaimed).div( mantissa() ); } /** * @notice PoolToken request to withdraw multiple PoolTokens allocated rewards * @param tokenIds Array of pool token id */ function withdrawMultiple(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, "TokensIds length must not be 0"); for (uint256 i = 0; i < tokenIds.length; i++) { withdraw(tokenIds[i]); } } /** * @notice PoolToken request to withdraw all allocated rewards * @param tokenId Pool token id */ function withdraw(uint256 tokenId) public { uint256 totalClaimableRewards = poolTokenClaimableRewards(tokenId); uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed; IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); address poolAddr = tokenInfo.pool; require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!"); require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken"); BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr); require(!pool.paused(), "Pool withdraw paused"); ITranchedPool tranchedPool = ITranchedPool(poolAddr); require(!tranchedPool.creditLine().isLate(), "Pool is late on payments"); tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(totalClaimableRewards); safeERC20Transfer(config.getGFI(), poolTokens.ownerOf(tokenId), totalClaimableRewards); emit BackerRewardsClaimed(_msgSender(), tokenId, totalClaimableRewards); } /* Internal functions */ function _allocateRewards(uint256 _interestPaymentAmount) internal { uint256 _totalInterestReceived = totalInterestReceived; if (usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) { return; } address _poolAddress = _msgSender(); // Gross GFI Rewards earned for incoming interest dollars uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount); ITranchedPool pool = ITranchedPool(_poolAddress); BackerRewardsInfo storage _poolInfo = pools[_poolAddress]; uint256 totalJuniorDeposits = pool.totalJuniorDeposits(); if (totalJuniorDeposits == 0) { return; } // example: (6708203932437400000000 * 10^18) / (100000*10^18) _poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add( newGrossRewards.mul(mantissa()).div(usdcToAtomic(totalJuniorDeposits)) ); totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount); } /** * @notice Calculate the rewards earned for a given interest payment * @param _interestPaymentAmount interest payment amount times 1e6 */ function _calculateNewGrossGFIRewardsForInterestAmount(uint256 _interestPaymentAmount) internal view returns (uint256) { uint256 totalGFISupply = config.getGFI().totalSupply(); // incoming interest payment, times * 1e18 divided by 1e6 uint256 interestPaymentAmount = usdcToAtomic(_interestPaymentAmount); // all-time interest payments prior to the incoming amount, times 1e18 uint256 _previousTotalInterestReceived = usdcToAtomic(totalInterestReceived); uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived); // sum of new interest payment + previous total interest payments, times 1e18 uint256 newTotalInterest = usdcToAtomic( atomicToUSDC(_previousTotalInterestReceived).add(atomicToUSDC(interestPaymentAmount)) ); // interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded if (newTotalInterest > maxInterestDollarsEligible) { newTotalInterest = maxInterestDollarsEligible; } /* equation: (sqrtNewTotalInterest-sqrtOrigTotalInterest) * totalRewardPercentOfTotalGFI / sqrtMaxInterestDollarsEligible / 100 * totalGFISupply / 10^18 example scenario: - new payment = 5000*10^18 - original interest received = 0*10^18 - total reward percent = 3 * 10^18 - max interest dollars = 1 * 10^27 ($1 billion) - totalGfiSupply = 100_000_000 * 10^18 example math: (70710678118 - 0) * 3000000000000000000 / 31622776601683 / 100 * 100000000000000000000000000 / 10^18 = 6708203932437400000000 (6,708.2039 GFI) */ uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest); uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible); require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero"); uint256 newGrossRewards = sqrtDiff .mul(totalRewardPercentOfTotalGFI) .div(sqrtMaxInterestDollarsEligible) .div(100) .mul(totalGFISupply) .div(mantissa()); // Extra safety check to make sure the logic is capped at a ceiling of potential rewards // Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount uint256 absoluteMaxGfiCheckPerDollar = Babylonian .sqrt((uint256)(1).mul(mantissa())) .mul(totalRewardPercentOfTotalGFI) .div(sqrtMaxInterestDollarsEligible) .div(100) .mul(totalGFISupply) .div(mantissa()); require( newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest), "newGrossRewards cannot be greater then the max gfi per dollar" ); return newGrossRewards; } function mantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function usdcToAtomic(uint256 amount) internal pure returns (uint256) { return amount.mul(mantissa()).div(usdcMantissa()); } function atomicToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(mantissa().div(usdcMantissa())); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ======== MODIFIERS ======== */ modifier onlyPool() { require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!"); _; } /* ======== EVENTS ======== */ event GoldfinchConfigUpdated(address indexed who, address configAddress); event BackerRewardsClaimed(address indexed owner, uint256 indexed tokenId, uint256 amount); event BackerRewardsSetTotalRewards(address indexed owner, uint256 totalRewards, uint256 totalRewardPercentOfTotalGFI); event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived); event BackerRewardsSetMaxInterestDollarsEligible(address indexed owner, uint256 maxInterestDollarsEligible); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas 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); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../rewards/BackerRewards.sol"; contract TestBackerRewards is BackerRewards { address payable public sender; // solhint-disable-next-line modifiers/ensure-modifiers function _setSender(address payable _sender) public { sender = _sender; } function _msgSender() internal view override returns (address payable) { if (sender != address(0)) { return sender; } else { return super._msgSender(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "../../external/ERC721PresetMinterPauserAutoId.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/IFidu.sol"; import "../core/BaseUpgradeablePausable.sol"; import "../core/GoldfinchConfig.sol"; import "../core/ConfigHelper.sol"; import "../../library/SafeERC20Transfer.sol"; contract TransferRestrictedVault is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe, SafeERC20Transfer { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; struct PoolTokenPosition { uint256 tokenId; uint256 lockedUntil; } struct FiduPosition { uint256 amount; uint256 lockedUntil; } // tokenId => poolTokenPosition mapping(uint256 => PoolTokenPosition) public poolTokenPositions; // tokenId => fiduPosition mapping(uint256 => FiduPosition) public fiduPositions; /* We are using our own initializer function so that OZ doesn't automatically set owner as msg.sender. Also, it lets us set our config contract */ // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __Context_init_unchained(); __AccessControl_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 Accredited Investor Tokens", "GFI-V2-AI"); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); config = _config; _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function depositJunior(ITranchedPool tranchedPool, uint256 amount) public nonReentrant { require(config.getGo().go(msg.sender), "This address has not been go-listed"); safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); approveSpender(address(tranchedPool), amount); uint256 poolTokenId = tranchedPool.deposit(uint256(ITranchedPool.Tranches.Junior), amount); uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays()); _tokenIdTracker.increment(); uint256 tokenId = _tokenIdTracker.current(); poolTokenPositions[tokenId] = PoolTokenPosition({ tokenId: poolTokenId, lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds) }); _mint(msg.sender, tokenId); } function depositJuniorWithPermit( ITranchedPool tranchedPool, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); depositJunior(tranchedPool, amount); } function depositSenior(uint256 amount) public nonReentrant { safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); ISeniorPool seniorPool = config.getSeniorPool(); approveSpender(address(seniorPool), amount); uint256 depositShares = seniorPool.deposit(amount); uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays()); _tokenIdTracker.increment(); uint256 tokenId = _tokenIdTracker.current(); fiduPositions[tokenId] = FiduPosition({ amount: depositShares, lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds) }); _mint(msg.sender, tokenId); } function depositSeniorWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); depositSenior(amount); } function withdrawSenior(uint256 tokenId, uint256 usdcAmount) public nonReentrant onlyTokenOwner(tokenId) { IFidu fidu = config.getFidu(); ISeniorPool seniorPool = config.getSeniorPool(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); uint256 receivedAmount = seniorPool.withdraw(usdcAmount); uint256 fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); FiduPosition storage fiduPosition = fiduPositions[tokenId]; uint256 fiduPositionAmount = fiduPosition.amount; require(fiduPositionAmount >= fiduUsed, "Not enough Fidu for withdrawal"); fiduPosition.amount = fiduPositionAmount.sub(fiduUsed); safeERC20Transfer(config.getUSDC(), msg.sender, receivedAmount); } function withdrawSeniorInFidu(uint256 tokenId, uint256 shares) public nonReentrant onlyTokenOwner(tokenId) { FiduPosition storage fiduPosition = fiduPositions[tokenId]; uint256 fiduPositionAmount = fiduPosition.amount; require(fiduPositionAmount >= shares, "Not enough Fidu for withdrawal"); fiduPosition.amount = fiduPositionAmount.sub(shares); uint256 usdcAmount = config.getSeniorPool().withdrawInFidu(shares); safeERC20Transfer(config.getUSDC(), msg.sender, usdcAmount); } function withdrawJunior(uint256 tokenId, uint256 amount) public nonReentrant onlyTokenOwner(tokenId) returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { PoolTokenPosition storage position = poolTokenPositions[tokenId]; require(position.lockedUntil > 0, "Position is empty"); IPoolTokens poolTokens = config.getPoolTokens(); uint256 poolTokenId = position.tokenId; IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(poolTokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); (interestWithdrawn, principalWithdrawn) = pool.withdraw(poolTokenId, amount); uint256 totalWithdrawn = interestWithdrawn.add(principalWithdrawn); safeERC20Transfer(config.getUSDC(), msg.sender, totalWithdrawn); return (interestWithdrawn, principalWithdrawn); } function _beforeTokenTransfer( address from, address to, uint256 tokenId // solhint-disable-line no-unused-vars ) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeSafe) { // AccreditedInvestor tokens can never be transferred. The underlying positions, // however, can be transferred after the timelock expires. require(from == address(0) || to == address(0), "TransferRestrictedVault tokens cannot be transferred"); } /** * @dev This method assumes that positions are mutually exclusive i.e. that the token * represents a position in either PoolTokens or Fidu, but not both. */ function transferPosition(uint256 tokenId, address to) public nonReentrant { require(ownerOf(tokenId) == msg.sender, "Cannot transfer position of token you don't own"); FiduPosition storage fiduPosition = fiduPositions[tokenId]; if (fiduPosition.lockedUntil > 0) { require( block.timestamp >= fiduPosition.lockedUntil, "Underlying position cannot be transferred until lockedUntil" ); transferFiduPosition(fiduPosition, to); delete fiduPositions[tokenId]; } PoolTokenPosition storage poolTokenPosition = poolTokenPositions[tokenId]; if (poolTokenPosition.lockedUntil > 0) { require( block.timestamp >= poolTokenPosition.lockedUntil, "Underlying position cannot be transferred until lockedUntil" ); transferPoolTokenPosition(poolTokenPosition, to); delete poolTokenPositions[tokenId]; } _burn(tokenId); } function transferPoolTokenPosition(PoolTokenPosition storage position, address to) internal { IPoolTokens poolTokens = config.getPoolTokens(); poolTokens.safeTransferFrom(address(this), to, position.tokenId); } function transferFiduPosition(FiduPosition storage position, address to) internal { IFidu fidu = config.getFidu(); safeERC20Transfer(fidu, to, position.amount); } function approveSpender(address spender, uint256 allowance) internal { IERC20withDec usdc = config.getUSDC(); safeERC20Approve(usdc, spender, allowance); } modifier onlyTokenOwner(uint256 tokenId) { require(ownerOf(tokenId) == msg.sender, "Only the token owner is allowed to call this function"); _; } } // SPDX-License-Identifier: MIT // solhint-disable pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // contract IOneSplitConsts { // // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ... // uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01; // uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated // uint256 internal constant FLAG_DISABLE_BANCOR = 0x04; // uint256 internal constant FLAG_DISABLE_OASIS = 0x08; // uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10; // uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20; // uint256 internal constant FLAG_DISABLE_CHAI = 0x40; // uint256 internal constant FLAG_DISABLE_AAVE = 0x80; // uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100; // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_BDAI = 0x400; // uint256 internal constant FLAG_DISABLE_IEARN = 0x800; // uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000; // uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000; // uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000; // uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000; // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000; // uint256 internal constant FLAG_DISABLE_WETH = 0x80000; // uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH // uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH // uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH // uint256 internal constant FLAG_DISABLE_IDLE = 0x800000; // uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000; // uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000; // uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000; // uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000; // uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000; // uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000; // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000; // uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000; // uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000; // uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000; // uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000; // uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000; // uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000; // uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000; // uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default // uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000; // uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000; // } interface IOneSplit { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) external view returns ( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) external payable returns (uint256 returnAmount); } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../Initializable.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 {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _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 { } uint256[44] private __gap; } pragma solidity ^0.6.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; import "../../Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./ERC20.sol"; import "../../Initializable.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 ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @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); } uint256[50] private __gap; } pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../token/ERC20/ERC20.sol"; import "../token/ERC20/ERC20Burnable.sol"; import "../token/ERC20/ERC20Pausable.sol"; import "../Initializable.sol"; /** * @dev {ERC20} 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 * * 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 aother accounts */ contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ function initialize(string memory name, string memory symbol) public { __ERC20PresetMinterPauser_init(name, symbol); } function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __ERC20PresetMinterPauser_init_unchained(name, symbol); } function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) { super._beforeTokenTransfer(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol"; import "./ConfigHelper.sol"; /** * @title Fidu * @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares * in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we * burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu * and USDC (or whatever currencies the Pool may allow withdraws in during the future) * @author Goldfinch */ contract Fidu is ERC20PresetMinterPauserUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); // $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC; uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; event GoldfinchConfigUpdated(address indexed who, address configAddress); /* We are using our own initializer function so we can set the owner by passing it in. I would override the regular "initializer" function, but I can't because it's not marked as "virtual" in the parent contract */ // solhint-disable-next-line func-name-mixedcase function __initialize__( address owner, string calldata name, string calldata symbol, GoldfinchConfig _config ) external initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); config = _config; _setupRole(MINTER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(MINTER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mintTo(address to, uint256 amount) public { require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch"); // This super call restricts to only the minter in its implementation, so we don't need to do it here. super.mint(to, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have the MINTER_ROLE */ function burnFrom(address from, uint256 amount) public override { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn"); require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch"); _burn(from, amount); } // Internal functions // canMint assumes that the USDC that backs the new shares has already been sent to the Pool function canMint(uint256 newAmount) internal view returns (bool) { ISeniorPool seniorPool = config.getSeniorPool(); uint256 liabilities = totalSupply().add(newAmount).mul(seniorPool.sharePrice()).div(fiduMantissa()); uint256 liabilitiesInDollars = fiduToUSDC(liabilities); uint256 _assets = seniorPool.assets(); if (_assets >= liabilitiesInDollars) { return true; } else { return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD; } } // canBurn assumes that the USDC that backed these shares has already been moved out the Pool function canBurn(uint256 amountToBurn) internal view returns (bool) { ISeniorPool seniorPool = config.getSeniorPool(); uint256 liabilities = totalSupply().sub(amountToBurn).mul(seniorPool.sharePrice()).div(fiduMantissa()); uint256 liabilitiesInDollars = fiduToUSDC(liabilities); uint256 _assets = seniorPool.assets(); if (_assets >= liabilitiesInDollars) { return true; } else { return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD; } } function fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(fiduMantissa().div(usdcMantissa())); } function fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function updateGoldfinchConfig() external { require(hasRole(OWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to change config"); config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./LeverageRatioStrategy.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ITranchedPool.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; contract FixedLeverageRatioStrategy is LeverageRatioStrategy { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) { return config.getLeverageRatio(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ITranchedPool.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; abstract contract LeverageRatioStrategy is BaseUpgradeablePausable, ISeniorPoolStrategy { using SafeMath for uint256; uint256 internal constant LEVERAGE_RATIO_DECIMALS = 1e18; /** * @notice Determines how much money to invest in the senior tranche based on what is committed to the junior * tranche, what is committed to the senior tranche, and a leverage ratio to the junior tranche. Because * it takes into account what is already committed to the senior tranche, the value returned by this * function can be used "idempotently" to achieve the investment target amount without exceeding that target. * @param seniorPool The senior pool to invest from * @param pool The tranched pool to invest into (as the senior) * @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool */ function invest(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) { ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); // If junior capital is not yet invested, or pool already locked, then don't invest anything. if (juniorTranche.lockedUntil == 0 || seniorTranche.lockedUntil > 0) { return 0; } return _invest(pool, juniorTranche, seniorTranche); } /** * @notice A companion of `invest()`: determines how much would be returned by `invest()`, as the * value to invest into the senior tranche, if the junior tranche were locked and the senior tranche * were not locked. * @param seniorPool The senior pool to invest from * @param pool The tranched pool to invest into (as the senior) * @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool */ function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) { ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); return _invest(pool, juniorTranche, seniorTranche); } function _invest( ITranchedPool pool, ITranchedPool.TrancheInfo memory juniorTranche, ITranchedPool.TrancheInfo memory seniorTranche ) internal view returns (uint256) { uint256 juniorCapital = juniorTranche.principalDeposited; uint256 existingSeniorCapital = seniorTranche.principalDeposited; uint256 seniorTarget = juniorCapital.mul(getLeverageRatio(pool)).div(LEVERAGE_RATIO_DECIMALS); if (existingSeniorCapital >= seniorTarget) { return 0; } return seniorTarget.sub(existingSeniorCapital); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./LeverageRatioStrategy.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ITranchedPool.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; contract DynamicLeverageRatioStrategy is LeverageRatioStrategy { bytes32 public constant LEVERAGE_RATIO_SETTER_ROLE = keccak256("LEVERAGE_RATIO_SETTER_ROLE"); struct LeverageRatioInfo { uint256 leverageRatio; uint256 juniorTrancheLockedUntil; } // tranchedPoolAddress => leverageRatioInfo mapping(address => LeverageRatioInfo) public ratios; event LeverageRatioUpdated( address indexed pool, uint256 leverageRatio, uint256 juniorTrancheLockedUntil, bytes32 version ); function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(LEVERAGE_RATIO_SETTER_ROLE, owner); _setRoleAdmin(LEVERAGE_RATIO_SETTER_ROLE, OWNER_ROLE); } function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) { LeverageRatioInfo memory ratioInfo = ratios[address(pool)]; ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); require(ratioInfo.juniorTrancheLockedUntil > 0, "Leverage ratio has not been set yet."); if (seniorTranche.lockedUntil > 0) { // The senior tranche is locked. Coherence check: we expect locking the senior tranche to have // updated `juniorTranche.lockedUntil` (compared to its value when `setLeverageRatio()` was last // called successfully). require( ratioInfo.juniorTrancheLockedUntil < juniorTranche.lockedUntil, "Expected junior tranche `lockedUntil` to have been updated." ); } else { require( ratioInfo.juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Leverage ratio is obsolete. Wait for its recalculation." ); } return ratioInfo.leverageRatio; } /** * @notice Updates the leverage ratio for the specified tranched pool. The combination of the * `juniorTranchedLockedUntil` param and the `version` param in the event emitted by this * function are intended to enable an outside observer to verify the computation of the leverage * ratio set by calls of this function. * @param pool The tranched pool whose leverage ratio to update. * @param leverageRatio The leverage ratio value to set for the tranched pool. * @param juniorTrancheLockedUntil The `lockedUntil` timestamp, of the tranched pool's * junior tranche, to which this calculation of `leverageRatio` corresponds, i.e. the * value of the `lockedUntil` timestamp of the JuniorCapitalLocked event which the caller * is calling this function in response to having observed. By providing this timestamp * (plus an assumption that we can trust the caller to report this value accurately), * the caller enables this function to enforce that a leverage ratio that is obsolete in * the sense of having been calculated for an obsolete `lockedUntil` timestamp cannot be set. * @param version An arbitrary identifier included in the LeverageRatioUpdated event emitted * by this function, enabling the caller to describe how it calculated `leverageRatio`. Using * the bytes32 type accommodates using git commit hashes (both the current SHA1 hashes, which * require 20 bytes; and the future SHA256 hashes, which require 32 bytes) for this value. */ function setLeverageRatio( ITranchedPool pool, uint256 leverageRatio, uint256 juniorTrancheLockedUntil, bytes32 version ) public onlySetterRole { ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); // NOTE: We allow a `leverageRatio` of 0. require( leverageRatio <= 10 * LEVERAGE_RATIO_DECIMALS, "Leverage ratio must not exceed 10 (adjusted for decimals)." ); require(juniorTranche.lockedUntil > 0, "Cannot set leverage ratio if junior tranche is not locked."); require(seniorTranche.lockedUntil == 0, "Cannot set leverage ratio if senior tranche is locked."); require(juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Invalid `juniorTrancheLockedUntil` timestamp."); ratios[address(pool)] = LeverageRatioInfo({ leverageRatio: leverageRatio, juniorTrancheLockedUntil: juniorTrancheLockedUntil }); emit LeverageRatioUpdated(address(pool), leverageRatio, juniorTrancheLockedUntil, version); } modifier onlySetterRole() { require( hasRole(LEVERAGE_RATIO_SETTER_ROLE, _msgSender()), "Must have leverage-ratio setter role to perform this action" ); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.5 <0.8.0; import "../token/ERC20/ERC20.sol"; import "./IERC20Permit.sol"; import "../cryptography/ECDSA.sol"; import "../utils/Counters.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) internal EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // 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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n รท 2 + 1, and for v in (282): v โˆˆ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) internal { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; /** * @title GFI * @notice GFI is Goldfinch's governance token. * @author Goldfinch */ contract GFI is Context, AccessControl, ERC20Burnable, ERC20Pausable { using SafeMath for uint256; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /// The maximum number of tokens that can be minted uint256 public cap; event CapUpdated(address indexed who, uint256 cap); constructor( address owner, string memory name, string memory symbol, uint256 initialCap ) public ERC20(name, symbol) { cap = initialCap; _setupRole(MINTER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(MINTER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /** * @notice create and send tokens to a specified address * @dev this function will fail if the caller attempts to mint over the current cap */ function mint(address account, uint256 amount) public onlyMinter whenNotPaused { require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap"); _mint(account, amount); } /** * @notice sets the maximum number of tokens that can be minted * @dev the cap must be greater than the current total supply */ function setCap(uint256 _cap) external onlyOwner { require(_cap >= totalSupply(), "Cannot decrease the cap below existing supply"); cap = _cap; emit CapUpdated(_msgSender(), cap); } function mintingAmountIsWithinCap(uint256 amount) internal returns (bool) { return totalSupply().add(amount) <= cap; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external onlyPauser { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external onlyPauser { _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } modifier onlyOwner() { require(hasRole(OWNER_ROLE, _msgSender()), "Must be owner"); _; } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "Must be minter"); _; } modifier onlyPauser() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must be pauser"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/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; /** * @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.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier:MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; // Taken from https://github.com/opengsn/forwarder/blob/master/contracts/Forwarder.sol and adapted to work locally // Main change is removing interface inheritance and adding a some debugging niceities contract TestForwarder { using ECDSA for bytes32; struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; } string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data"; string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; // solhint-disable-line max-line-length mapping(bytes32 => bool) public typeHashes; mapping(bytes32 => bool) public domains; // Nonces of senders, used to prevent replay attacks mapping(address => uint256) private nonces; // solhint-disable-next-line no-empty-blocks receive() external payable {} function getNonce(address from) public view returns (uint256) { return nonces[from]; } constructor() public { string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")")); registerRequestTypeInternal(requestType); } function verify( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external view { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); } function execute( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external payable returns (bool success, bytes memory ret) { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); _updateNonce(req); // solhint-disable-next-line avoid-low-level-calls (success, ret) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from)); // Added by Goldfinch for debugging if (!success) { require(success, string(ret)); } if (address(this).balance > 0) { //can't fail: req.from signed (off-chain) the request, so it must be an EOA... payable(req.from).transfer(address(this).balance); } return (success, ret); } function _verifyNonce(ForwardRequest memory req) internal view { require(nonces[req.from] == req.nonce, "nonce mismatch"); } function _updateNonce(ForwardRequest memory req) internal { nonces[req.from]++; } function registerRequestType(string calldata typeName, string calldata typeSuffix) external { for (uint256 i = 0; i < bytes(typeName).length; i++) { bytes1 c = bytes(typeName)[i]; require(c != "(" && c != ")", "invalid typename"); } string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix)); registerRequestTypeInternal(requestType); } function registerDomainSeparator(string calldata name, string calldata version) external { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } bytes memory domainValue = abi.encode( keccak256(bytes(EIP712_DOMAIN_TYPE)), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ); bytes32 domainHash = keccak256(domainValue); domains[domainHash] = true; emit DomainRegistered(domainHash, domainValue); } function registerRequestTypeInternal(string memory requestType) internal { bytes32 requestTypehash = keccak256(bytes(requestType)); typeHashes[requestTypehash] = true; emit RequestTypeRegistered(requestTypehash, requestType); } event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue); event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr); function _verifySig( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig ) internal view { require(domains[domainSeparator], "unregistered domain separator"); require(typeHashes[requestTypeHash], "unregistered request typehash"); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData))) ); require(digest.recover(sig) == req.from, "signature mismatch"); } function _getEncoded( ForwardRequest memory req, bytes32 requestTypeHash, bytes memory suffixData ) public pure returns (bytes memory) { return abi.encodePacked( requestTypeHash, abi.encode(req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)), suffixData ); } } // contracts/GLDToken.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/ERC20Permit.sol"; contract TestERC20 is ERC20("USD Coin", "USDC"), ERC20Permit("USD Coin") { constructor(uint256 initialSupply, uint8 decimals) public { _setupDecimals(decimals); _mint(msg.sender, initialSupply); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../external/ERC721PresetMinterPauserAutoId.sol"; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IPoolTokens.sol"; /** * @title PoolTokens * @notice PoolTokens is an ERC721 compliant contract, which can represent * junior tranche or senior tranche shares of any of the borrower pools. * @author Goldfinch */ contract PoolTokens is IPoolTokens, ERC721PresetMinterPauserAutoIdUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; struct PoolInfo { uint256 totalMinted; uint256 totalPrincipalRedeemed; bool created; } // tokenId => tokenInfo mapping(uint256 => TokenInfo) public tokens; // poolAddress => poolInfo mapping(address => PoolInfo) public pools; event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); event GoldfinchConfigUpdated(address indexed who, address configAddress); /* We are using our own initializer function so that OZ doesn't automatically set owner as msg.sender. Also, it lets us set our config contract */ // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __Context_init_unchained(); __AccessControl_init_unchained(); __ERC165_init_unchained(); // This is setting name and symbol of the NFT's __ERC721_init_unchained("Goldfinch V2 Pool Tokens", "GFI-V2-PT"); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); config = _config; _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /** * @notice Called by pool to create a debt position in a particular tranche and amount * @param params Struct containing the tranche and the amount * @param to The address that should own the position * @return tokenId The token ID (auto-incrementing integer across all pools) */ function mint(MintParams calldata params, address to) external virtual override onlyPool whenNotPaused returns (uint256 tokenId) { address poolAddress = _msgSender(); tokenId = createToken(params, poolAddress); _mint(to, tokenId); config.getBackerRewards().setPoolTokenAccRewardsPerPrincipalDollarAtMint(_msgSender(), tokenId); emit TokenMinted(to, poolAddress, tokenId, params.principalAmount, params.tranche); return tokenId; } /** * @notice Updates a token to reflect the principal and interest amounts that have been redeemed. * @param tokenId The token id to update (must be owned by the pool calling this function) * @param principalRedeemed The incremental amount of principal redeemed (cannot be more than principal deposited) * @param interestRedeemed The incremental amount of interest redeemed */ function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external virtual override onlyPool whenNotPaused { TokenInfo storage token = tokens[tokenId]; address poolAddr = token.pool; require(token.pool != address(0), "Invalid tokenId"); require(_msgSender() == poolAddr, "Only the token's pool can redeem"); PoolInfo storage pool = pools[poolAddr]; pool.totalPrincipalRedeemed = pool.totalPrincipalRedeemed.add(principalRedeemed); require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot redeem more than we minted"); token.principalRedeemed = token.principalRedeemed.add(principalRedeemed); require( token.principalRedeemed <= token.principalAmount, "Cannot redeem more than principal-deposited amount for token" ); token.interestRedeemed = token.interestRedeemed.add(interestRedeemed); emit TokenRedeemed(ownerOf(tokenId), poolAddr, tokenId, principalRedeemed, interestRedeemed, token.tranche); } /** * @dev Burns a specific ERC721 token, and removes the data from our mappings * @param tokenId uint256 id of the ERC721 token to be burned. */ function burn(uint256 tokenId) external virtual override whenNotPaused { TokenInfo memory token = _getTokenInfo(tokenId); bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId); bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender(); address owner = ownerOf(tokenId); require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token"); require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens"); destroyAndBurn(tokenId); emit TokenBurned(owner, token.pool, tokenId); } function getTokenInfo(uint256 tokenId) external view virtual override returns (TokenInfo memory) { return _getTokenInfo(tokenId); } /** * @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem * tokens * @param newPool The address of the newly created pool */ function onPoolCreated(address newPool) external override onlyGoldfinchFactory { pools[newPool].created = true; } /** * @notice Returns a boolean representing whether the spender is the owner or the approved spender of the token * @param spender The address to check * @param tokenId The token id to check for * @return True if approved to redeem/transfer/burn the token, false if not */ function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) { return _isApprovedOrOwner(spender, tokenId); } function validPool(address sender) public view virtual override returns (bool) { return _validPool(sender); } function createToken(MintParams calldata params, address poolAddress) internal returns (uint256 tokenId) { PoolInfo storage pool = pools[poolAddress]; _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); tokens[tokenId] = TokenInfo({ pool: poolAddress, tranche: params.tranche, principalAmount: params.principalAmount, principalRedeemed: 0, interestRedeemed: 0 }); pool.totalMinted = pool.totalMinted.add(params.principalAmount); return tokenId; } function destroyAndBurn(uint256 tokenId) internal { delete tokens[tokenId]; _burn(tokenId); } function _validPool(address poolAddress) internal view virtual returns (bool) { return pools[poolAddress].created; } function _getTokenInfo(uint256 tokenId) internal view returns (TokenInfo memory) { return tokens[tokenId]; } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyGoldfinchFactory() { require(_msgSender() == config.goldfinchFactoryAddress(), "Only Goldfinch factory is allowed"); _; } modifier onlyPool() { require(_validPool(_msgSender()), "Invalid pool!"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/PoolTokens.sol"; contract TestPoolTokens is PoolTokens { bool public disablePoolValidation; address payable public sender; // solhint-disable-next-line modifiers/ensure-modifiers function _disablePoolValidation(bool shouldDisable) public { disablePoolValidation = shouldDisable; } // solhint-disable-next-line modifiers/ensure-modifiers function _setSender(address payable _sender) public { sender = _sender; } function _validPool(address _sender) internal view override returns (bool) { if (disablePoolValidation) { return true; } else { return super._validPool(_sender); } } function _msgSender() internal view override returns (address payable) { if (sender != address(0)) { return sender; } else { return super._msgSender(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; import "./IV1CreditLine.sol"; import "./ITranchedPool.sol"; abstract contract IMigratedTranchedPool is ITranchedPool { function migrateCreditLineToV2( IV1CreditLine clToMigrate, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) external virtual returns (IV2CreditLine); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IV1CreditLine { address public borrower; address public underwriter; uint256 public limit; uint256 public interestApr; uint256 public paymentPeriodInDays; uint256 public termInDays; uint256 public lateFeeApr; uint256 public balance; uint256 public interestOwed; uint256 public principalOwed; uint256 public termEndBlock; uint256 public nextDueBlock; uint256 public interestAccruedAsOfBlock; uint256 public writedownAmount; uint256 public lastFullPaymentBlock; function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./TranchedPool.sol"; import "../../interfaces/IV1CreditLine.sol"; import "../../interfaces/IMigratedTranchedPool.sol"; contract MigratedTranchedPool is TranchedPool, IMigratedTranchedPool { bool public migrated; function migrateCreditLineToV2( IV1CreditLine clToMigrate, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) external override returns (IV2CreditLine) { require(msg.sender == config.creditDeskAddress(), "Only credit desk can call this"); require(!migrated, "Already migrated"); // Set accounting state vars. IV2CreditLine newCl = creditLine; newCl.setBalance(clToMigrate.balance()); newCl.setInterestOwed(clToMigrate.interestOwed()); newCl.setPrincipalOwed(clToMigrate.principalOwed()); newCl.setTermEndTime(termEndTime); newCl.setNextDueTime(nextDueTime); newCl.setInterestAccruedAsOf(interestAccruedAsOf); newCl.setLastFullPaymentTime(lastFullPaymentTime); newCl.setTotalInterestAccrued(totalInterestPaid.add(clToMigrate.interestOwed())); migrateDeposits(clToMigrate, totalInterestPaid); migrated = true; return newCl; } function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal { // Mint junior tokens to the SeniorPool, equal to current cl balance; require(!locked(), "Pool has been locked"); // Hardcode to always get the JuniorTranche, since the migration case is when // the senior pool took the entire investment. Which we're expressing as the junior tranche uint256 tranche = uint256(ITranchedPool.Tranches.Junior); TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche has been locked"); trancheInfo.principalDeposited = clToMigrate.limit(); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({ tranche: tranche, principalAmount: trancheInfo.principalDeposited }); IPoolTokens poolTokens = config.getPoolTokens(); uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress()); uint256 balancePaid = creditLine.limit().sub(creditLine.balance()); // Account for the implicit redemptions already made by the Legacy Pool _lockJuniorCapital(poolSlices.length - 1); _lockPool(); PoolSlice storage currentSlice = poolSlices[poolSlices.length - 1]; currentSlice.juniorTranche.lockedUntil = block.timestamp - 1; poolTokens.redeem(tokenId, balancePaid, totalInterestPaid); // Simulate the drawdown currentSlice.juniorTranche.principalSharePrice = 0; currentSlice.seniorTranche.principalSharePrice = 0; // Set junior's sharePrice correctly currentSlice.juniorTranche.applyByAmount(totalInterestPaid, balancePaid, totalInterestPaid, balancePaid); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./Accountant.sol"; import "./CreditLine.sol"; import "./GoldfinchFactory.sol"; import "../../interfaces/IV1CreditLine.sol"; import "../../interfaces/IMigratedTranchedPool.sol"; /** * @title Goldfinch's CreditDesk contract * @notice Main entry point for borrowers and underwriters. * Handles key logic for creating CreditLine's, borrowing money, repayment, etc. * @author Goldfinch */ contract CreditDesk is BaseUpgradeablePausable, ICreditDesk { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; struct Underwriter { uint256 governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentApplied( address indexed payer, address indexed creditLine, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount ); event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; mapping(address => address) private creditLines; /** * @notice Run only once, on initialization * @param owner The address of who should have the "OWNER_ROLE" of this contract * @param _config The address of the GoldfinchConfig contract */ function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } /** * @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create" * @param underwriterAddress The address of the underwriter for whom the limit shall change * @param limit What the new limit will be set to * Requirements: * * - the caller must have the `OWNER_ROLE`. */ function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external override onlyAdmin whenNotPaused { require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol"); underwriters[underwriterAddress].governanceLimit = limit; emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit); } /** * @notice Allows a borrower to drawdown on their creditline. * `amount` USDC is sent to the borrower, and the credit line accounting is updated. * @param creditLineAddress The creditline from which they would like to drawdown * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown * * Requirements: * * - the caller must be the borrower on the creditLine */ function drawdown(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); Borrower storage borrower = borrowers[msg.sender]; require(borrower.creditLines.length > 0, "No credit lines exist for this borrower"); require(amount > 0, "Must drawdown more than zero"); require(cl.borrower() == msg.sender, "You are not the borrower of this credit line"); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); uint256 unappliedBalance = getUSDCBalance(creditLineAddress); require( withinCreditLimit(amount, unappliedBalance, cl), "The borrower does not have enough credit limit for this drawdown" ); uint256 balance = cl.balance(); if (balance == 0) { cl.setInterestAccruedAsOf(currentTime()); cl.setLastFullPaymentTime(currentTime()); } IPool pool = config.getPool(); // If there is any balance on the creditline that has not been applied yet, then use that first before // drawing down from the pool. This is to support cases where the borrower partially pays back the // principal before the due date, but then decides to drawdown again uint256 amountToTransferFromCL; if (unappliedBalance > 0) { if (amount > unappliedBalance) { amountToTransferFromCL = unappliedBalance; amount = amount.sub(unappliedBalance); } else { amountToTransferFromCL = amount; amount = 0; } bool success = pool.transferFrom(creditLineAddress, msg.sender, amountToTransferFromCL); require(success, "Failed to drawdown"); } (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, currentTime()); balance = balance.add(amount); updateCreditLineAccounting(cl, balance, interestOwed, principalOwed); // Must put this after we update the credit line accounting, so we're using the latest // interestOwed require(!isLate(cl, currentTime()), "Cannot drawdown when payments are past due"); emit DrawdownMade(msg.sender, address(cl), amount.add(amountToTransferFromCL)); if (amount > 0) { bool success = pool.drawdown(msg.sender, amount); require(success, "Failed to drawdown"); } } /** * @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to * the individual CreditLine), but it is not *applied* unless it is after the nextDueTime, or until we assess * the credit line (ie. payment period end). * Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective * interest rate). If there is still any left over, it will remain in the USDC Balance * of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's. * @param creditLineAddress The credit line to be paid back * @param amount The amount, in USDC atomic units, that a borrower wishes to pay */ function pay(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { require(amount > 0, "Must pay more than zero"); CreditLine cl = CreditLine(creditLineAddress); collectPayment(cl, amount); assessCreditLine(creditLineAddress); } /** * @notice Assesses a particular creditLine. This will apply payments, which will update accounting and * distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone * is allowed to call it. * @param creditLineAddress The creditline that should be assessed. */ function assessCreditLine(address creditLineAddress) public override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); // Do not assess until a full period has elapsed or past due require(cl.balance() > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < cl.nextDueTime() && !isLate(cl, currentTime())) { return; } uint256 timeToAssess = calculateNextDueTime(cl); cl.setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } _applyPayment(cl, getUSDCBalance(address(cl)), timeToAssess); } function applyPayment(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); require(cl.borrower() == msg.sender, "You do not belong to this credit line"); _applyPayment(cl, amount, currentTime()); } function migrateV1CreditLine( address _clToMigrate, address borrower, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) public onlyAdmin returns (address, address) { IV1CreditLine clToMigrate = IV1CreditLine(_clToMigrate); uint256 originalBalance = clToMigrate.balance(); require(clToMigrate.limit() > 0, "Can't migrate empty credit line"); require(originalBalance > 0, "Can't migrate credit line that's currently paid off"); // Ensure it is a v1 creditline by calling a function that only exists on v1 require(clToMigrate.nextDueBlock() > 0, "Invalid creditline"); if (borrower == address(0)) { borrower = clToMigrate.borrower(); } // We're migrating from 1e8 decimal precision of interest rates to 1e18 // So multiply the legacy rates by 1e10 to normalize them. uint256 interestMigrationFactor = 1e10; uint256[] memory allowedUIDTypes; address pool = getGoldfinchFactory().createMigratedPool( borrower, 20, // junior fee percent clToMigrate.limit(), clToMigrate.interestApr().mul(interestMigrationFactor), clToMigrate.paymentPeriodInDays(), clToMigrate.termInDays(), clToMigrate.lateFeeApr(), 0, 0, allowedUIDTypes ); IV2CreditLine newCl = IMigratedTranchedPool(pool).migrateCreditLineToV2( clToMigrate, termEndTime, nextDueTime, interestAccruedAsOf, lastFullPaymentTime, totalInterestPaid ); // Close out the original credit line clToMigrate.setLimit(0); clToMigrate.setBalance(0); // Some sanity checks on the migration require(newCl.balance() == originalBalance, "Balance did not migrate properly"); require(newCl.interestAccruedAsOf() == interestAccruedAsOf, "Interest accrued as of did not migrate properly"); return (address(newCl), pool); } /** * @notice Simple getter for the creditlines of a given underwriter * @param underwriterAddress The underwriter address you would like to see the credit lines of. */ function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } /** * @notice Simple getter for the creditlines of a given borrower * @param borrowerAddress The borrower address you would like to see the credit lines of. */ function getBorrowerCreditLines(address borrowerAddress) public view returns (address[] memory) { return borrowers[borrowerAddress].creditLines; } /** * @notice This function is only meant to be used by frontends. It returns the total * payment due for a given creditLine as of the provided timestamp. Returns 0 if no * payment is due (e.g. asOf is before the nextDueTime) * @param creditLineAddress The creditLine to calculate the payment for * @param asOf The timestamp to use for the payment calculation, if it is set to 0, uses the current time */ function getNextPaymentAmount(address creditLineAddress, uint256 asOf) external view override onlyValidCreditLine(creditLineAddress) returns (uint256) { if (asOf == 0) { asOf = currentTime(); } CreditLine cl = CreditLine(creditLineAddress); if (asOf < cl.nextDueTime() && !isLate(cl, currentTime())) { return 0; } (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( cl, asOf, config.getLatenessGracePeriodInDays() ); return cl.interestOwed().add(interestAccrued).add(cl.principalOwed().add(principalAccrued)); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); } /* * Internal Functions */ /** * @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line. * Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be collected */ function collectPayment(CreditLine cl, uint256 amount) internal { require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); emit PaymentCollected(msg.sender, address(cl), amount); bool success = config.getPool().transferFrom(msg.sender, address(cl), amount); require(success, "Failed to collect payment"); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function _applyPayment( CreditLine cl, uint256 amount, uint256 timestamp ) internal { (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment( cl, amount, timestamp ); IPool pool = config.getPool(); if (interestPayment > 0 || principalPayment > 0) { emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); pool.collectInterestAndPrincipal(address(cl), interestPayment, principalPayment); } } function handlePayment( CreditLine cl, uint256 paymentAmount, uint256 timestamp ) internal returns ( uint256, uint256, uint256 ) { (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, cl.balance(), interestOwed, principalOwed ); uint256 newBalance = cl.balance().sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = cl.balance().sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( cl, newBalance, interestOwed.sub(pa.interestPayment), principalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function isLate(CreditLine cl, uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(cl.lastFullPaymentTime()); return secondsElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); } function getGoldfinchFactory() internal view returns (GoldfinchFactory) { return GoldfinchFactory(config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory))); } function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( cl, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. cl.setInterestAccruedAsOf(timestamp); } return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued)); } function withinCreditLimit( uint256 amount, uint256 unappliedBalance, CreditLine cl ) internal view returns (bool) { return cl.balance().add(amount).sub(unappliedBalance) <= cl.limit(); } function withinTransactionLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit)); } function calculateNewTermEndTime(CreditLine cl, uint256 balance) internal view returns (uint256) { // If there's no balance, there's no loan, so there's no term end time if (balance == 0) { return 0; } // Don't allow any weird bugs where we add to your current end time. This // function should only be used on new credit lines, when we are setting them up if (cl.termEndTime() != 0) { return cl.termEndTime(); } return currentTime().add(SECONDS_PER_DAY.mul(cl.termInDays())); } function calculateNextDueTime(CreditLine cl) internal view returns (uint256) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); uint256 balance = cl.balance(); uint256 nextDueTime = cl.nextDueTime(); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (nextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* nextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= nextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(nextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); nextDueTime = nextDueTime.add(secondsToAdvance); return Math.min(nextDueTime, cl.termEndTime()); } // Your paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && nextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the nextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < nextDueTime) { return nextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter) internal view returns (bool) { uint256 underwriterLimit = underwriter.governanceLimit; require(underwriterLimit != 0, "underwriter does not have governance limit"); uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter); uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount); return totalToBeExtended <= underwriterLimit; } function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit)); } function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) { uint256 creditExtended; uint256 length = underwriter.creditLines.length; for (uint256 i = 0; i < length; i++) { CreditLine cl = CreditLine(underwriter.creditLines[i]); creditExtended = creditExtended.add(cl.limit()); } return creditExtended; } function updateCreditLineAccounting( CreditLine cl, uint256 balance, uint256 interestOwed, uint256 principalOwed ) internal nonReentrant { // subtract cl from total loans outstanding totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance()); cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 nextDueTime = cl.nextDueTime(); if (interestOwed == 0 && nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < nextDueTime) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); mostRecentLastDueTime = nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = nextDueTime; } cl.setLastFullPaymentTime(mostRecentLastDueTime); } // Add new amount back to total loans outstanding totalLoansOutstanding = totalLoansOutstanding.add(balance); cl.setTermEndTime(calculateNewTermEndTime(cl, balance)); // pass in balance as a gas optimization cl.setNextDueTime(calculateNextDueTime(cl)); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } modifier onlyValidCreditLine(address clAddress) { require(creditLines[clAddress] != address(0), "Unknown credit line"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/CreditDesk.sol"; contract TestCreditDesk is CreditDesk { // solhint-disable-next-line modifiers/ensure-modifiers function _setTotalLoansOutstanding(uint256 amount) public { totalLoansOutstanding = amount; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../core/BaseUpgradeablePausable.sol"; import "../core/ConfigHelper.sol"; import "../core/CreditLine.sol"; import "../core/GoldfinchConfig.sol"; import "../../interfaces/IMigrate.sol"; /** * @title V2 Migrator Contract * @notice This is a one-time use contract solely for the purpose of migrating from our V1 * to our V2 architecture. It will be temporarily granted authority from the Goldfinch governance, * and then revokes it's own authority and transfers it back to governance. * @author Goldfinch */ contract V2Migrator is BaseUpgradeablePausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); using SafeMath for uint256; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; mapping(address => address) public borrowerContracts; event CreditLineMigrated(address indexed owner, address indexed clToMigrate, address newCl, address tranchedPool); function initialize(address owner, address _config) external initializer { require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); } function migratePhase1(GoldfinchConfig newConfig) external onlyAdmin { pauseEverything(); migrateToNewConfig(newConfig); migrateToSeniorPool(newConfig); } function migrateCreditLines( GoldfinchConfig newConfig, address[][] calldata creditLinesToMigrate, uint256[][] calldata migrationData ) external onlyAdmin { IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress()); IGoldfinchFactory factory = newConfig.getGoldfinchFactory(); for (uint256 i = 0; i < creditLinesToMigrate.length; i++) { address[] calldata clData = creditLinesToMigrate[i]; uint256[] calldata data = migrationData[i]; address clAddress = clData[0]; address owner = clData[1]; address borrowerContract = borrowerContracts[owner]; if (borrowerContract == address(0)) { borrowerContract = factory.createBorrower(owner); borrowerContracts[owner] = borrowerContract; } (address newCl, address pool) = creditDesk.migrateV1CreditLine( clAddress, borrowerContract, data[0], data[1], data[2], data[3], data[4] ); emit CreditLineMigrated(owner, clAddress, newCl, pool); } } function bulkAddToGoList(GoldfinchConfig newConfig, address[] calldata members) external onlyAdmin { newConfig.bulkAddToGoList(members); } function pauseEverything() internal { IMigrate(config.creditDeskAddress()).pause(); IMigrate(config.poolAddress()).pause(); IMigrate(config.fiduAddress()).pause(); } function migrateToNewConfig(GoldfinchConfig newConfig) internal { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); config.setAddress(key, address(newConfig)); IMigrate(config.creditDeskAddress()).updateGoldfinchConfig(); IMigrate(config.poolAddress()).updateGoldfinchConfig(); IMigrate(config.fiduAddress()).updateGoldfinchConfig(); IMigrate(config.goldfinchFactoryAddress()).updateGoldfinchConfig(); key = uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds); newConfig.setNumber(key, 24 * 60 * 60); key = uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays); newConfig.setNumber(key, 365); key = uint256(ConfigOptions.Numbers.LeverageRatio); // 1e18 is the LEVERAGE_RATIO_DECIMALS newConfig.setNumber(key, 3 * 1e18); } function upgradeImplementations(GoldfinchConfig _config, address[] calldata newDeployments) public { address newPoolAddress = newDeployments[0]; address newCreditDeskAddress = newDeployments[1]; address newFiduAddress = newDeployments[2]; address newGoldfinchFactoryAddress = newDeployments[3]; bytes memory data; IMigrate pool = IMigrate(_config.poolAddress()); IMigrate creditDesk = IMigrate(_config.creditDeskAddress()); IMigrate fidu = IMigrate(_config.fiduAddress()); IMigrate goldfinchFactory = IMigrate(_config.goldfinchFactoryAddress()); // Upgrade implementations pool.changeImplementation(newPoolAddress, data); creditDesk.changeImplementation(newCreditDeskAddress, data); fidu.changeImplementation(newFiduAddress, data); goldfinchFactory.changeImplementation(newGoldfinchFactoryAddress, data); } function migrateToSeniorPool(GoldfinchConfig newConfig) internal { IMigrate(config.fiduAddress()).grantRole(MINTER_ROLE, newConfig.seniorPoolAddress()); IMigrate(config.poolAddress()).unpause(); IMigrate(newConfig.poolAddress()).migrateToSeniorPool(); } function closeOutMigration(GoldfinchConfig newConfig) external onlyAdmin { IMigrate fidu = IMigrate(newConfig.fiduAddress()); IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress()); IMigrate oldPool = IMigrate(newConfig.poolAddress()); IMigrate goldfinchFactory = IMigrate(newConfig.goldfinchFactoryAddress()); fidu.unpause(); fidu.renounceRole(MINTER_ROLE, address(this)); fidu.renounceRole(OWNER_ROLE, address(this)); fidu.renounceRole(PAUSER_ROLE, address(this)); creditDesk.renounceRole(OWNER_ROLE, address(this)); creditDesk.renounceRole(PAUSER_ROLE, address(this)); oldPool.renounceRole(OWNER_ROLE, address(this)); oldPool.renounceRole(PAUSER_ROLE, address(this)); goldfinchFactory.renounceRole(OWNER_ROLE, address(this)); goldfinchFactory.renounceRole(PAUSER_ROLE, address(this)); config.renounceRole(PAUSER_ROLE, address(this)); config.renounceRole(OWNER_ROLE, address(this)); newConfig.renounceRole(OWNER_ROLE, address(this)); newConfig.renounceRole(PAUSER_ROLE, address(this)); newConfig.renounceRole(GO_LISTER_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IMigrate { function pause() public virtual; function unpause() public virtual; function updateGoldfinchConfig() external virtual; function grantRole(bytes32 role, address assignee) external virtual; function renounceRole(bytes32 role, address self) external virtual; // Proxy methods function transferOwnership(address newOwner) external virtual; function changeImplementation(address newImplementation, bytes calldata data) external virtual; function owner() external view virtual returns (address); // CreditDesk function migrateV1CreditLine( address _clToMigrate, address borrower, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) public virtual returns (address, address); // Pool function migrateToSeniorPool() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Pool.sol"; contract TestPool is Pool { function _getNumShares(uint256 amount) public view returns (uint256) { return getNumShares(amount); } function _usdcMantissa() public pure returns (uint256) { return usdcMantissa(); } function _fiduMantissa() public pure returns (uint256) { return fiduMantissa(); } function _usdcToFidu(uint256 amount) public pure returns (uint256) { return usdcToFidu(amount); } function _setSharePrice(uint256 newSharePrice) public returns (uint256) { sharePrice = newSharePrice; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Pool.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; contract FakeV2CreditLine is BaseUpgradeablePausable { // Credit line terms address public borrower; address public underwriter; uint256 public limit; uint256 public interestApr; uint256 public paymentPeriodInDays; uint256 public termInDays; uint256 public lateFeeApr; // Accounting variables uint256 public balance; uint256 public interestOwed; uint256 public principalOwed; uint256 public termEndTime; uint256 public nextDueTime; uint256 public interestAccruedAsOf; uint256 public writedownAmount; uint256 public lastFullPaymentTime; function initialize( address owner, address _borrower, address _underwriter, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public initializer { __BaseUpgradeablePausable__init(owner); borrower = _borrower; underwriter = _underwriter; limit = _limit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; interestAccruedAsOf = block.timestamp; } function anotherNewFunction() external pure returns (uint256) { return 42; } function authorizePool(address) external view onlyAdmin { // no-op return; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../interfaces/IGo.sol"; import "../../interfaces/IUniqueIdentity0612.sol"; contract Go is IGo, BaseUpgradeablePausable { address public override uniqueIdentity; using SafeMath for uint256; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; GoldfinchConfig public legacyGoList; uint256[11] public allIdTypes; event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize( address owner, GoldfinchConfig _config, address _uniqueIdentity ) public initializer { require( owner != address(0) && address(_config) != address(0) && _uniqueIdentity != address(0), "Owner and config and UniqueIdentity addresses cannot be empty" ); __BaseUpgradeablePausable__init(owner); _performUpgrade(); config = _config; uniqueIdentity = _uniqueIdentity; } function updateGoldfinchConfig() external override onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function performUpgrade() external onlyAdmin { return _performUpgrade(); } function _performUpgrade() internal { allIdTypes[0] = ID_TYPE_0; allIdTypes[1] = ID_TYPE_1; allIdTypes[2] = ID_TYPE_2; allIdTypes[3] = ID_TYPE_3; allIdTypes[4] = ID_TYPE_4; allIdTypes[5] = ID_TYPE_5; allIdTypes[6] = ID_TYPE_6; allIdTypes[7] = ID_TYPE_7; allIdTypes[8] = ID_TYPE_8; allIdTypes[9] = ID_TYPE_9; allIdTypes[10] = ID_TYPE_10; } /** * @notice sets the config that will be used as the source of truth for the go * list instead of the config currently associated. To use the associated config for to list, set the override * to the null address. */ function setLegacyGoList(GoldfinchConfig _legacyGoList) external onlyAdmin { legacyGoList = _legacyGoList; } /** * @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol * for any of the UID token types. * This status is defined as: whether `balanceOf(account, id)` on the UniqueIdentity * contract is non-zero (where `id` is a supported token id on UniqueIdentity), falling back to the * account's status on the legacy go-list maintained on GoldfinchConfig. * @param account The account whose go status to obtain * @return The account's go status */ function go(address account) public view override returns (bool) { require(account != address(0), "Zero address is not go-listed"); if (_getLegacyGoList().goList(account) || IUniqueIdentity0612(uniqueIdentity).balanceOf(account, ID_TYPE_0) > 0) { return true; } // start loop at index 1 because we checked index 0 above for (uint256 i = 1; i < allIdTypes.length; ++i) { uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, allIdTypes[i]); if (idTypeBalance > 0) { return true; } } return false; } /** * @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol * for defined UID token types * @param account The account whose go status to obtain * @param onlyIdTypes Array of id types to check balances * @return The account's go status */ function goOnlyIdTypes(address account, uint256[] memory onlyIdTypes) public view override returns (bool) { require(account != address(0), "Zero address is not go-listed"); GoldfinchConfig goListSource = _getLegacyGoList(); for (uint256 i = 0; i < onlyIdTypes.length; ++i) { if (onlyIdTypes[i] == ID_TYPE_0 && goListSource.goList(account)) { return true; } uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, onlyIdTypes[i]); if (idTypeBalance > 0) { return true; } } return false; } /** * @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol. * @param account The account whose go status to obtain * @return The account's go status */ function goSeniorPool(address account) public view override returns (bool) { require(account != address(0), "Zero address is not go-listed"); if (account == config.stakingRewardsAddress() || _getLegacyGoList().goList(account)) { return true; } uint256[2] memory seniorPoolIdTypes = [ID_TYPE_0, ID_TYPE_1]; for (uint256 i = 0; i < seniorPoolIdTypes.length; ++i) { uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, seniorPoolIdTypes[i]); if (idTypeBalance > 0) { return true; } } return false; } function _getLegacyGoList() internal view returns (GoldfinchConfig) { return address(legacyGoList) == address(0) ? config : legacyGoList; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @dev This interface provides a subset of the functionality of the IUniqueIdentity /// interface -- namely, the subset of functionality needed by Goldfinch protocol contracts /// compiled with Solidity version 0.6.12. interface IUniqueIdentity0612 { function balanceOf(address account, uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/GoldfinchConfig.sol"; contract TestTheConfig { address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE; address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6; address public goldfinchFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9; address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96; address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4; address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5; address public trustedForwarderAddress = 0x956868751Cc565507B3B58E53a6f9f41B56bed74; address public cUSDCAddress = 0x5B281A6DdA0B271e91ae35DE655Ad301C976edb1; address public goldfinchConfigAddress = address(8); function testTheEnums(address configAddress) public { GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds), 8); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays), 9); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LeverageRatio), 10); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress); GoldfinchConfig(configAddress).setAddress( uint256(ConfigOptions.Addresses.GoldfinchFactory), goldfinchFactoryAddress ); GoldfinchConfig(configAddress).setAddress( uint256(ConfigOptions.Addresses.TrustedForwarder), trustedForwarderAddress ); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CUSDCContract), cUSDCAddress); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig), goldfinchConfigAddress); GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/GoldfinchConfig.sol"; contract TestGoldfinchConfig is GoldfinchConfig { function setAddressForTest(uint256 addressKey, address newAddress) public { addresses[addressKey] = newAddress; } }
You must have just done your first drawdown Active loan that has entered a new period, so return the next nextDueTime. But never return something after the termEndTime Your paid off, or have not taken out a loan yet, so no next due time. Active loan in current period, where we've already set the nextDueTime correctly, so should not change.
function calculateNextDueTime(CreditLine cl) internal view returns (uint256) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); uint256 balance = cl.balance(); uint256 nextDueTime = cl.nextDueTime(); uint256 curTimestamp = currentTime(); if (nextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } if (balance > 0 && curTimestamp >= nextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(nextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); nextDueTime = nextDueTime.add(secondsToAdvance); return Math.min(nextDueTime, cl.termEndTime()); } if (balance == 0 && nextDueTime != 0) { return 0; } if (balance > 0 && curTimestamp < nextDueTime) { return nextDueTime; } revert("Error: could not calculate next due time."); }
6,235,637
./partial_match/1/0x5BB837766F98dF4e761E63e33ea5C46292d6fA82/sources/contracts/AriaLand.sol
Internal method to fetch random number between 1 to 10k/
function _setRandomBlindNumber(uint256 input) public returns (uint256) { require( input >= 1 && input <= 10000, "Input must be between 1 and 10000." ); uint256 randomNumber = uint256( keccak256( abi.encodePacked( block.timestamp, blockhash(block.number), input ) ) ); randomBlindNumber[input] = (randomNumber % 10000) + 1; return randomBlindNumber[input]; }
3,539,658
./full_match/4/0x690DBCBcD018871668F8ED69f42247b77eE65C77/sources/contracts/3_Ballot.sol
Calls winningProposal() function to get the index of the winner contained in the proposals array and then return winnerName_ the name of the winner/
function winnerName() public view returns (bytes32 winnerName_) { winnerName_ = proposals[winningProposal()].name; }
661,046
pragma solidity ^0.5; import './base/openzeppelin/math/SafeMath.sol'; import './base/openzeppelin/token/ERC20/IERC20.sol'; import './Macros.sol'; import './Nonpayable.sol'; import './IMarket.sol'; /// @title ERC20 token "proxy" contract for upcity resources. /// @author lawrence forman ([email protected]) /// @dev Most logic is deferred to the UpcityMarket contract instance, /// which maintians the balances and supply of each token. The only real /// responsibility of this contract is to manage spending allowances. contract UpcityResourceTokenProxy is IERC20, Nonpayable { using SafeMath for uint256; uint8 private constant NUM_RESOURCES = $$(NUM_RESOURCES); string public name; string public symbol; uint8 public constant decimals = 18; /// @dev The UpcityMarket contract. IMarket private _market; /// @dev Spending allowances for each spender for a wallet. /// The mapping order is wallet -> spender -> allowance. mapping(address=>mapping(address=>uint256)) private _allowances; /// @dev Creates the contract. /// @param _name Token name /// @param _symbol Token symbol /// @param market The market address. constructor( string memory _name, string memory _symbol, address market) public { name = _name; symbol = _symbol; _market = IMarket(market); } /// @dev Get the current supply of tokens. /// @return The current supply of tokens (in wei). function totalSupply() external view returns (uint256) { // Query the market. return _market.getSupply(address(this)); } /// @dev Get the token balance of an address. /// @param who The address that owns the tokens. /// @return The balance of an address (in wei). function balanceOf(address who) external view returns (uint256) { // Query the market. return _market.getBalance(address(this), who); } /// @dev Get the spending allowance for a spender and owner pair. /// @param owner The address that owns the tokens. /// @param spender The address that has been given an allowance to spend /// from `owner`. /// @return The remaining spending allowance (in wei). function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /// @dev Grant an allowance to `spender` from the caller's wallet. /// This allowance will be reduced every time a successful /// transferFrom() occurs. /// @param spender The wallet's spender. /// @param value The allowance amount. function approve(address spender, uint256 value) external returns (bool) { // Overwrite the previous allowance. _allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Transfer tokens from the caller's wallet. /// Reverts if the caller does not have the funds to cover the transfer. /// @param to The recipient. /// @param amt The number of tokens to send (in wei) function transfer(address to, uint256 amt) external returns (bool) { // Let the market handle it. This call should revert on failure. _transfer(msg.sender, to, amt); return true; } /// @dev Transfer tokens from a wallet. /// Reverts if the `from` does not have the funds to cover the transfer /// or the caller does not have enough allowance. /// @param from The wallet to spend tokens from. /// @param to The recipient. /// @param amt The number of tokens to send (in wei) function transferFrom(address from, address to, uint256 amt) external returns (bool) { // Ensure that the spender has enough allowance. uint256 remaining = _allowances[from][msg.sender]; require(remaining >= amt, ERROR_INSUFFICIENT); // Reduce the allowance. _allowances[from][msg.sender] = remaining - amt; _transfer(from, to, amt); return true; } /// @dev Perform an unchecked transfer between addresses. /// @param from The sender address. /// @param to The receiver address/ /// @param amt The amount of tokens to transfer, in wei. function _transfer(address from, address to, uint256 amt) private { require(to != address(0x0) && to != address(this), ERROR_INVALID); // This should revert if the balances are insufficient. _market.proxyTransfer(from, to, amt); emit Transfer(from, to, amt); } }
Transfer tokens from the caller's wallet. Reverts if the caller does not have the funds to cover the transfer. to The recipient. amt The number of tokens to send (in wei) Let the market handle it. This call should revert on failure.
function transfer(address to, uint256 amt) external returns (bool) { _transfer(msg.sender, to, amt); return true; }
1,043,224
./full_match/1/0x567c09B55294998d7a6F2A3A948e8fD331531B88/sources/contracts/UMA/common/implementation/FixedPoint.sol
Whether `a` is less than `b`. a a FixedPoint. b a FixedPoint. return True if `a < b`, or False./
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; }
9,749,016
./full_match/1/0xb30044cFF3c3a2FB362646f20b396567C04c297f/sources/project:/contracts/MTokenAdmin.sol
Reduces reserves for mToken by transferring to admin Requires fresh interest accrual mToken The mToken whose reserves to reduce reduceAmount Amount of reduction to reserves return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller is admin We fail gracefully unless market's block number equals current block number
function _reduceReservesFresh(uint240 mToken, uint reduceAmount) internal returns (uint) { MathError mathErr; uint totalReservesNew; uint totalCashNew; address payable admin = getAdmin(); if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } if (accrualBlockNumber[mToken] != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } if (mathErr != MathError.NO_ERROR) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } if (mathErr != MathError.NO_ERROR) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } doTransferOut(admin, underlyingID, reduceAmount, 0, address(0), ""); totalCashUnderlying[mToken] = totalCashNew; emit ReservesReduced(admin, mToken, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); }
17,163,265
// SPDX-License-Identifier: MIT pragma solidity^0.8.0; import "./openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./openzeppelin/contracts/access/Ownable.sol"; import "./openzeppelin/contracts/utils/math/SafeMath.sol"; import "./openzeppelin/contracts/utils/Address.sol"; import "./openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol"; interface IUniswapRouter is ISwapRouter { function refundETH() external payable; } contract RugstoreIO is Ownable, ERC721Enumerable { using SafeMath for uint256; using Strings for uint256; uint public constant max_supply = 3333; IQuoter public constant quoter = IQuoter(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6); address private constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant pebble = 0xDC98c5543F3004DEBfaad8966ec403093D0aa4A8; address public constant weaver = 0x500c579764fA743c49392293086D53632817bC25; uint256 public pebblePrice; uint256 _pebble; uint256 public constant ethprice = 12500000000000000; uint256 public constant mintprice = 25000000000000000; uint[] public priceDog; uint[] public priceAgld; uint[] public priceAsh; IERC20 DOG=IERC20(0xBAac2B4491727D78D2b78815144570b9f2Fe8899); IERC20 PEBBLE=IERC20(0xDC98c5543F3004DEBfaad8966ec403093D0aa4A8); IERC20 ASH=IERC20(0x64D91f12Ece7362F91A6f8E7940Cd55F05060b92); IERC20 AGLD=IERC20(0x32353A6C91143bfd6C7d363B546e62a9A2489A20); bool public isActive = false; mapping (uint256 => string) private _tokenURIs; string private _baseURIextended; constructor() ERC721("Rugstore", "RUG") { } function rug() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function balanceEth() public view returns(uint256) { uint balance = address(this).balance; return balance; } function initializeRug() public onlyOwner { isActive = !isActive; for(uint i = 0; i < 3; i++) { uint mintIndex = totalSupply(); if (totalSupply() < max_supply) { _safeMint(msg.sender, mintIndex); } } } //BASEURI STUFF function setBaseURI(string memory baseURI_) external onlyOwner() { _baseURIextended = baseURI_; } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId)); _tokenURIs[tokenId] = _tokenURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIextended; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId)); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); string memory json = ".json"; // 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, json)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString(), json)); } function mintRugWithEth(uint numberOfTokens) public payable { require(isActive); require(numberOfTokens > 0 && numberOfTokens <= 25); require(totalSupply().add(numberOfTokens) <= max_supply); require(msg.value >= mintprice.mul(numberOfTokens)); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < max_supply) { _safeMint(msg.sender, mintIndex); } } } function mintRugWithDog(uint numberOfTokens) public { require(isActive); require(numberOfTokens > 0 && numberOfTokens <= 15); require(totalSupply() < max_supply); DOG.transferFrom(msg.sender, weaver, priceDog[1].mul(numberOfTokens)); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < max_supply) { _safeMint(msg.sender, mintIndex); } } } function mintRugWithAgld(uint numberOfTokens) public { require(isActive); require(numberOfTokens > 0 && numberOfTokens <= 15); require(totalSupply() < max_supply); AGLD.transferFrom(msg.sender, weaver, priceAgld[1].mul(numberOfTokens)); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < max_supply) { _safeMint(msg.sender, mintIndex); } } } function mintRugWithAsh(uint numberOfTokens) public { require(isActive); require(numberOfTokens > 0 && numberOfTokens <= 15); require(totalSupply() < max_supply); ASH.transferFrom(msg.sender, weaver, priceAsh[1].mul(numberOfTokens)); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < max_supply) { _safeMint(msg.sender, mintIndex); } } } function mintRugWithPebble(uint numberOfTokens) public { require(isActive); require(numberOfTokens > 0 && numberOfTokens <= 15); require(totalSupply() < max_supply); PEBBLE.transferFrom(msg.sender, weaver, pebblePrice.mul(numberOfTokens)); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < max_supply) { _safeMint(msg.sender, mintIndex); } } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function getDogPriceSushi(uint _eth_amount) public view returns(uint[] memory amount) { address[] memory path = new address[](2); path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; path[1] = 0xBAac2B4491727D78D2b78815144570b9f2Fe8899; uint256[] memory result = SushiV2.getAmountsOut(_eth_amount, path); return result; } function getAGLDPriceSushi(uint _eth_amount) public view returns(uint[] memory amount) { address[] memory path = new address[](2); path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; path[1] = 0x32353A6C91143bfd6C7d363B546e62a9A2489A20; uint256[] memory result = SushiV2.getAmountsOut(_eth_amount, path); return result; } function getASHPriceUNI(uint _eth_amount) public view returns(uint[] memory amount) { address[] memory path = new address[](2); path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; path[1] = 0x64D91f12Ece7362F91A6f8E7940Cd55F05060b92; uint256[] memory result = UniV2.getAmountsOut(_eth_amount, path); return result; } function showDogPriceSushi() public view returns(uint256) { return priceDog[1]; } function showASHPriceUNI() public view returns(uint256) { return priceAsh[1]; } function showAGLDPriceSushi() public view returns(uint256) { return priceAgld[1]; } function setPriceDog() public { priceDog = getDogPriceSushi(12500000000000000); } function setPriceAGLD() public { priceAgld = getAGLDPriceSushi(12500000000000000); } function setPriceASH() public { priceAsh = getASHPriceUNI(12500000000000000); } function setPrices() public { priceDog = getDogPriceSushi(12500000000000000); priceAgld = getAGLDPriceSushi(12500000000000000); priceAsh = getASHPriceUNI(12500000000000000); _pebble = getEstimatedPebbleforEth(1); pebblePrice = ethprice * _pebble; } function setPebblePrice() public { _pebble = getEstimatedPebbleforEth(1); pebblePrice = ethprice * _pebble; } function showPebblePrice() public view returns(uint256) { return pebblePrice; } //using sushiv2 UniswapRouter SushiV2 = UniswapRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //uni-v2 UniswapRouter UniV2 = UniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /*@dev get AGLD price via UNI-V3 */ function getEstimatedPebbleforEth(uint uniAmount) public payable returns (uint256) { address tokenIn = pebble; address tokenOut = WETH9; uint24 fee = 10000; uint160 sqrtPriceLimitX96 = 0; return quoter.quoteExactOutputSingle( tokenIn, tokenOut, fee, uniAmount, sqrtPriceLimitX96 ); } } interface UniswapRouter { function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; }
If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId)); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); string memory json = ".json"; if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI, json)); } }
7,026,162
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "sol-temple/src/tokens/ERC721.sol"; import "sol-temple/src/utils/Auth.sol"; import "sol-temple/src/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** * @title Ape Runners * @author naomsa <https://twitter.com/naomsa666> */ contract ApeRunners is Auth, Pausable, ERC721("Ape Runners", "AR") { using Strings for uint256; using MerkleProof for bytes32[]; /// @notice Max supply. uint256 public constant MAX_SUPPLY = 5000; /// @notice Max amount per claim (public sale). uint256 public constant MAX_PER_TX = 10; /// @notice Claim price. uint256 public constant PRICE = 0.04 ether; /// @notice 0 = CLOSED, 1 = WHITELIST, 2 = PUBLIC. uint256 public saleState; /// @notice Metadata base URI. string public baseURI; /// @notice Metadata URI extension. string public baseExtension; /// @notice Unrevealed metadata URI. string public unrevealedURI; /// @notice Whitelist merkle root. bytes32 public merkleRoot; /// @notice Whitelist mints per address. mapping(address => uint256) public whitelistMinted; /// @notice OpenSea proxy registry. address public opensea; /// @notice LooksRare marketplace transfer manager. address public looksrare; /// @notice Check if marketplaces pre-approve is enabled. bool public marketplacesApproved = true; constructor( string memory unrevealedURI_, bytes32 merkleRoot_, address opensea_, address looksrare_ ) { unrevealedURI = unrevealedURI_; merkleRoot = merkleRoot_; opensea = opensea_; looksrare = looksrare_; for (uint256 i = 0; i < 50; i++) _safeMint(msg.sender, i); } /// @notice Claim one or more tokens. function claim(uint256 amount_) external payable { uint256 supply = totalSupply(); require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded"); if (msg.sender != owner()) { require(saleState == 2, "Public sale is not open"); require(amount_ > 0 && amount_ <= MAX_PER_TX, "Invalid claim amount"); require(msg.value == PRICE * amount_, "Invalid ether amount"); } for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++); } /// @notice Claim one or more tokens for whitelisted user. function claimWhitelist(uint256 amount_, bytes32[] memory proof_) external payable { uint256 supply = totalSupply(); require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded"); if (msg.sender != owner()) { require(saleState == 1, "Whitelist sale is not open"); require( amount_ > 0 && amount_ + whitelistMinted[msg.sender] <= MAX_PER_TX, "Invalid claim amount" ); require(msg.value == PRICE * amount_, "Invalid ether amount"); require(isWhitelisted(msg.sender, proof_), "Invalid proof"); } whitelistMinted[msg.sender] += amount_; for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++); } /// @notice Retrieve if `user_` is whitelisted based on his `proof_`. function isWhitelisted(address user_, bytes32[] memory proof_) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(user_)); return proof_.verify(merkleRoot, leaf); } /** * @notice See {IERC721-tokenURI}. * @dev In order to make a metadata reveal, there must be an unrevealedURI string, which * gets set on the constructor and, for optimization purposes, when the owner() sets a new * baseURI, the unrevealedURI gets deleted, saving gas and triggering a reveal. */ function tokenURI(uint256 tokenId_) public view override returns (string memory) { if (bytes(unrevealedURI).length > 0) return unrevealedURI; return string(abi.encodePacked(baseURI, tokenId_.toString(), baseExtension)); } /// @notice Set baseURI to `baseURI_`, baseExtension to `baseExtension_` and deletes unrevealedURI, triggering a reveal. function setBaseURI(string memory baseURI_, string memory baseExtension_) external onlyAuthorized { baseURI = baseURI_; baseExtension = baseExtension_; delete unrevealedURI; } /// @notice Set unrevealedURI to `unrevealedURI_`. function setUnrevealedURI(string memory unrevealedURI_) external onlyAuthorized { unrevealedURI = unrevealedURI_; } /// @notice Set unrevealedURI to `unrevealedURI_`. function setSaleState(uint256 saleState_) external onlyAuthorized { saleState = saleState_; } /// @notice Set merkleRoot to `merkleRoot_`. function setMerkleRoot(bytes32 merkleRoot_) external onlyAuthorized { merkleRoot = merkleRoot_; } /// @notice Set opensea to `opensea_`. function setOpensea(address opensea_) external onlyAuthorized { opensea = opensea_; } /// @notice Set looksrare to `looksrare_`. function setLooksrare(address looksrare_) external onlyAuthorized { looksrare = looksrare_; } /// @notice Toggle pre-approve feature state for sender. function toggleMarketplacesApproved() external onlyAuthorized { marketplacesApproved = !marketplacesApproved; } /// @notice Toggle paused state. function togglePaused() external onlyAuthorized { _togglePaused(); } /** * @notice Withdraw `amount_` of ether to msg.sender. * @dev Combined with the Auth util, this function can be called by * anyone with the authorization from the owner, so a team member can * get his shares with a permissioned call and exact data. */ function withdraw(uint256 amount_) external onlyAuthorized { payable(msg.sender).transfer(amount_); } /// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (!marketplacesApproved) return super.isApprovedForAll(owner, operator); return operator == OpenSeaProxyRegistry(opensea).proxies(owner) || operator == looksrare || super.isApprovedForAll(owner, operator); } /// @dev Edited in order to block transfers while paused unless msg.sender is the owner(). function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { require( msg.sender == owner() || paused() == false, "Pausable: contract paused" ); super._beforeTokenTransfer(from, to, tokenId); } } contract OpenSeaProxyRegistry { mapping(address => address) public proxies; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; /** * @title ERC721 * @author naomsa <https://twitter.com/naomsa666> * @notice A complete ERC721 implementation including metadata and enumerable * functions. Completely gas optimized and extensible. */ abstract contract ERC721 { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @dev This emits when ownership of any NFT changes by any mechanism. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice See {IERC721Metadata-name}. string public name; /// @notice See {IERC721Metadata-symbol}. string public symbol; /// @notice Array of all owners. address[] private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token ID to approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {IERC721-balanceOf}. function balanceOf(address owner) public view virtual returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balanceOf[owner]; } /// @notice See {IERC721-ownerOf}. function ownerOf(uint256 tokenId) public view virtual returns (address) { require(_exists(tokenId), "ERC721: query for nonexistent token"); address owner = _owners[tokenId]; return owner; } /// @notice See {IERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {IERC721-approve}. function approve(address to, uint256 tokenId) public virtual { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to, tokenId); } /// @notice See {IERC721-getApproved}. function getApproved(uint256 tokenId) public view virtual returns (address) { require(_exists(tokenId), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId]; } /// @notice See {IERC721-setApprovalForAll}. function setApprovalForAll(address operator, bool approved) public virtual { _setApprovalForAll(msg.sender, operator, approved); } /// @notice See {IERC721-isApprovedForAll} function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { return _isApprovedForAll[owner][operator]; } /// @notice See {IERC721-transferFrom}. function transferFrom( address from, address to, uint256 tokenId ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /// @notice See {IERC721-safeTransferFrom}. function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual { safeTransferFrom(from, to, tokenId, ""); } /// @notice See {IERC721-safeTransferFrom}. function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, data_); } /// @notice See {IERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (owner == _owners[i]) { if (count == index) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {IERC721Enumerable.totalSupply}. function totalSupply() public view virtual returns (uint256) { return _owners.length; } /// @notice See {IERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index) public view virtual returns (uint256) { require(index < _owners.length, "ERC721Enumerable: Index out of bounds"); return index; } /// @notice Returns a list of all token Ids owned by `owner`. function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 balance = balanceOf(owner); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /** * @notice 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); _checkOnERC721Received(from, to, tokenId, data_); } /** * @notice 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 tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @notice 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: query for nonexistent token"); address owner = _owners[tokenId]; return (spender == owner || getApproved(tokenId) == spender || _isApprovedForAll[owner][spender]); } /** * @notice 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, ""); } /** * @notice Same as {_safeMint}, but 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); _checkOnERC721Received(address(0), to, tokenId, data_); } /** * @notice Mints `tokenId` and transfers it to `to`. * * Requirements: * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); unchecked { _balanceOf[to]++; } emit Transfer(address(0), to, tokenId); } /** * @notice Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); delete _owners[tokenId]; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId); } /** * @notice Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(_owners[tokenId] == from, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; unchecked { _balanceOf[from]--; _balanceOf[to]++; } emit Transfer(from, to, tokenId); } /** * @notice Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(_owners[tokenId], to, tokenId); } /** * @notice 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"); _isApprovedForAll[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @notice Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param data bytes optional data to send along with the call */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private { if (to.code.length > 0) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /** * @notice 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. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /* ___ _ _ _ _ __ _ __ */ /* /',__)( ) ( )( '_`\ /'__`\( '__) */ /* \__, \| (_) || (_) )( ___/| | */ /* (____/`\___/'| ,__/'`\____)(_) */ /* | | */ /* (_) */ /// @notice See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == 0x80ac58cd || // ERC721 interfaceId == 0x5b5e139f || // ERC721Metadata interfaceId == 0x780e9d63 || // ERC721Enumerable interfaceId == 0x01ffc9a7; // ERC165 } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) external returns (bytes4); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; /** * @title Auth * @author naomsa <https://twitter.com/naomsa666> * @notice Authing system where the `owner` can authorize function calls * to other addresses as well as control the contract by his own. */ abstract contract Auth { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice Emited when the ownership is transfered. event OwnershipTransfered(address indexed from, address indexed to); /// @notice Emited a new call with `data` is authorized to `to`. event AuthorizationGranted(address indexed to, bytes data); /// @notice Emited a new call with `data` is forbidden to `to`. event AuthorizationForbidden(address indexed to, bytes data); /// @notice Contract's owner address. address private _owner; /// @notice A mapping to retrieve if a call data was authed and is valid for the address. mapping(address => mapping(bytes => bool)) private _isAuthorized; /** * @notice A modifier that requires the user to be the owner or authorization to call. * After the call, the user loses it's authorization if he's not the owner. */ modifier onlyAuthorized() { require(isAuthorized(msg.sender, msg.data), "Auth: sender is not the owner or authorized to call"); _; if (msg.sender != _owner) _isAuthorized[msg.sender][msg.data] = false; } /// @notice A simple modifier just to check whether the sender is the owner. modifier onlyOwner() { require(msg.sender == _owner, "Auth: sender is not the owner"); _; } /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor() { _transferOwnership(msg.sender); } /// @notice Returns the current contract owner. function owner() public view returns (address) { return _owner; } /// @notice Retrieves whether `user_` is authorized to call with `data_`. function isAuthorized(address user_, bytes memory data_) public view returns (bool) { return user_ == _owner || _isAuthorized[user_][data_]; } /// @notice Set the owner address to `owner_`. function transferOwnership(address owner_) public onlyOwner { require(_owner != owner_, "Auth: transfering ownership to current owner"); _transferOwnership(owner_); } /// @notice Set the owner address to `owner_`. Does not require anything function _transferOwnership(address owner_) internal { address oldOwner = _owner; _owner = owner_; emit OwnershipTransfered(oldOwner, owner_); } /// @notice Authorize a call with `data_` to the address `to_`. function auth(address to_, bytes memory data_) public onlyOwner { require(to_ != _owner, "Auth: authorizing call to the owner"); require(!_isAuthorized[to_][data_], "Auth: authorized calls cannot be authed"); _isAuthorized[to_][data_] = true; emit AuthorizationGranted(to_, data_); } /// @notice Authorize a call with `data_` to the address `to_`. function forbid(address to_, bytes memory data_) public onlyOwner { require(_isAuthorized[to_][data_], "Auth: unauthorized calls cannot be forbidden"); delete _isAuthorized[to_][data_]; emit AuthorizationForbidden(to_, data_); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; /** * @title Pausable * @author naomsa <https://twitter.com/naomsa666> * @notice Freeze your contract with a secure paused mechanism. */ abstract contract Pausable { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice Emited when the contract is paused. event Paused(address indexed by); /// @notice Emited when the contract is unpaused. event Unpaused(address indexed by); /// @notice Read-only pause state. bool private _paused; /// @notice A modifier to be used when the contract must be paused. modifier onlyWhenPaused() { require(_paused, "Pausable: contract not paused"); _; } /// @notice A modifier to be used when the contract must be unpaused. modifier onlyWhenUnpaused() { require(!_paused, "Pausable: contract paused"); _; } /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ /// @notice Retrieve contracts pause state. function paused() public view returns (bool) { return _paused; } /// @notice Inverts pause state. Declared internal so it can be combined with the Auth contract. function _togglePaused() internal { _paused = !_paused; if (_paused) emit Unpaused(msg.sender); else emit Paused(msg.sender); } } // 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/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } }
Authorize a call with `data_` to the address `to_`.
function forbid(address to_, bytes memory data_) public onlyOwner { require(_isAuthorized[to_][data_], "Auth: unauthorized calls cannot be forbidden"); delete _isAuthorized[to_][data_]; emit AuthorizationForbidden(to_, data_); }
5,470,702
pragma solidity ^0.6.0; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import './interfaces/IOracle.sol'; import './utils/Epoch.sol'; /** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */ contract Treasury is Epoch { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ address public cash; address public oracle; address public shareMasterChef; address public boardroom; uint256 public cashShareLpPoolPid; uint256 public constant cashPriceOne = 10 ** 18; uint256 public cashPriceDelta; uint256 public maxInflationRate = 20; // div by 100 uint256 public constant pointAddRate = 5; uint256 public constant pointSubRate = 10; uint256 public constant feeAddRate = 1; uint256 public constant feeSubRate = 5; // update oracle and get updated price // if above $1, tune parameter and allocate cash inflation reward to boardroom // if below $1, tune parameter constructor( address _cash, address _oracle, address _shareMasterChef, address _boardroom, uint256 _cashShareLpPoolPid, uint256 _starttime, uint256 _peroid ) public Epoch(_peroid, _starttime, 0){ cash = _cash; oracle = _oracle; shareMasterChef = _shareMasterChef; boardroom = _boardroom; cashShareLpPoolPid = _cashShareLpPoolPid; cashPriceDelta = 10 ** 16; } /* ========== VIEW FUNCTIONS ========== */ // oracle function getOraclePrice() public view returns (uint256) { return _getCashPrice(oracle); } function _getCashPrice(address _oracle) internal view returns (uint256) { try IOracle(_oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== MUTABLE FUNCTIONS ========== */ function _updateCashPrice() internal { try IOracle(oracle).update() {} catch {} } function allocateReward() external checkStartTime checkEpoch { _updateCashPrice(); uint256 cashPrice = _getCashPrice(oracle); // circulating supply uint256 cashSupply = IERC20(cash).totalSupply(); uint256 totalPoints = IMasterChef(shareMasterChef).totalAllocPoint(); uint256 lpPoints = IMasterChef(shareMasterChef).poolPoint(cashShareLpPoolPid); uint256 cashFee = ICash(cash).fee(); uint256 FEE_ONE = 10 ** 6; if (cashPrice >= cashPriceOne.add(cashPriceDelta)) { if (cashFee > 0) { uint256 subFee = FEE_ONE.mul(feeSubRate).div(100); cashFee = cashFee > subFee ? cashFee.sub(subFee) : 0; ICash(cash).setFee(cashFee); } if (lpPoints > 0) { uint256 subPoints = totalPoints.mul(pointSubRate).div(100); lpPoints = lpPoints > subPoints ? lpPoints.sub(subPoints) : 0; IMasterChef(shareMasterChef).set(cashShareLpPoolPid, lpPoints, true); } uint256 inflation = cashSupply.mul( cashPrice.sub(cashPriceOne) ).div(10 ** 18).div(10); if (inflation > cashSupply.mul(maxInflationRate).div(100)) { inflation = cashSupply.mul(maxInflationRate).div(100); } IBoardroom(boardroom).allocateReward(inflation); } if (cashPrice <= cashPriceOne.sub(cashPriceDelta)) { if (lpPoints >= totalPoints.div(2)) { // add cash transfer fee cashFee = cashFee.add(FEE_ONE.mul(feeAddRate).div(100)); if (cashFee > FEE_ONE.div(2)) { cashFee = FEE_ONE.div(2); } ICash(cash).setFee(cashFee); } else { lpPoints = lpPoints.add(totalPoints.mul(pointAddRate).div(100)); IMasterChef(shareMasterChef).set(cashShareLpPoolPid, lpPoints, true); } } } /* ========= GOV ============= */ function setCashPriceDelta(uint256 delta) public onlyOwner { cashPriceDelta = delta; } function setCashShareLpPoolPid(uint256 _pid) public onlyOwner { cashShareLpPoolPid = _pid; } function setMaxInflationRatio(uint256 _rate) public onlyOwner { maxInflationRate = _rate; } } interface ICash { function setFee(uint256 _fee) external; function fee() external view returns(uint256); } interface IMasterChef { function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function totalAllocPoint() external view returns(uint256); function poolPoint(uint256 _pid) external view returns (uint256); } interface IBoardroom { function allocateReward(uint256 amount) external; }
circulating supply add cash transfer fee
function allocateReward() external checkStartTime checkEpoch { _updateCashPrice(); uint256 cashPrice = _getCashPrice(oracle); uint256 cashSupply = IERC20(cash).totalSupply(); uint256 totalPoints = IMasterChef(shareMasterChef).totalAllocPoint(); uint256 lpPoints = IMasterChef(shareMasterChef).poolPoint(cashShareLpPoolPid); uint256 cashFee = ICash(cash).fee(); uint256 FEE_ONE = 10 ** 6; if (cashPrice >= cashPriceOne.add(cashPriceDelta)) { if (cashFee > 0) { uint256 subFee = FEE_ONE.mul(feeSubRate).div(100); cashFee = cashFee > subFee ? cashFee.sub(subFee) : 0; ICash(cash).setFee(cashFee); } if (lpPoints > 0) { uint256 subPoints = totalPoints.mul(pointSubRate).div(100); lpPoints = lpPoints > subPoints ? lpPoints.sub(subPoints) : 0; IMasterChef(shareMasterChef).set(cashShareLpPoolPid, lpPoints, true); } uint256 inflation = cashSupply.mul( cashPrice.sub(cashPriceOne) ).div(10 ** 18).div(10); if (inflation > cashSupply.mul(maxInflationRate).div(100)) { inflation = cashSupply.mul(maxInflationRate).div(100); } IBoardroom(boardroom).allocateReward(inflation); } if (cashPrice <= cashPriceOne.sub(cashPriceDelta)) { if (lpPoints >= totalPoints.div(2)) { cashFee = cashFee.add(FEE_ONE.mul(feeAddRate).div(100)); if (cashFee > FEE_ONE.div(2)) { cashFee = FEE_ONE.div(2); } ICash(cash).setFee(cashFee); lpPoints = lpPoints.add(totalPoints.mul(pointAddRate).div(100)); IMasterChef(shareMasterChef).set(cashShareLpPoolPid, lpPoints, true); } } }
12,740,478
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } import "./AfrikanBar.sol"; // MansaMusa is the master of Yetu. He can make Yetu and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once YETU is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MansaMusa is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP 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 YETUs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accYetuPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accYetuPerShare` (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 { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. YETUs to distribute per block. uint256 lastRewardBlock; // Last block number that YETUs distribution occurs. uint256 accYetuPerShare; // Accumulated YETUs per share, times 1e12. See below. } // The YETU TOKEN! YetubitToken public yetu; // The AFRIKAN TOKEN! AfrikanBar public afrikan; // Dev address. address public devaddr; // YETU tokens created per block. uint256 public yetuPerBlock; // Bonus muliplier for early yetu makers. uint256 public BONUS_MULTIPLIER = 1; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when YETU mining starts. uint256 public startBlock; // Public mapping to store if lp tokens has been included mapping(IBEP20 => bool) public farmRegistry; 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 SetDev(address indexed invoker, address indexed _devaddr); event SetMigrator(address indexed _migrator); event UpdateMultiplier(uint256 indexed multiplierNumber); modifier validatePoolByPid(uint256 _pid) { require (_pid < poolInfo.length , "Pool does not exist") ; _; } constructor( YetubitToken _yetu, AfrikanBar _afrikan, address _devaddr, uint256 _yetuPerBlock, uint256 _startBlock ) public { yetu = _yetu; afrikan = _afrikan; devaddr = _devaddr; yetuPerBlock = _yetuPerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _yetu, allocPoint: 1000, lastRewardBlock: startBlock, accYetuPerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; emit UpdateMultiplier(multiplierNumber); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { require(farmRegistry[_lpToken] == false, "Farm already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accYetuPerShare: 0 })); updateStakingPool(); farmRegistry[_lpToken] = true; } // Update the given pool's YETU allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner validatePoolByPid(_pid) { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending YETUs on frontend. function pendingYetu(uint256 _pid, address _user) external validatePoolByPid(_pid) view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accYetuPerShare = pool.accYetuPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 yetuReward = multiplier.mul(yetuPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accYetuPerShare = accYetuPerShare.add(yetuReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accYetuPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 yetuReward = multiplier.mul(yetuPerBlock).mul(pool.allocPoint).div(totalAllocPoint); yetu.mint(yetuReward.mul(11).div(10)); yetu.transfer(devaddr, yetuReward.div(10)); yetu.transfer(address(afrikan), yetuReward); pool.accYetuPerShare = pool.accYetuPerShare.add(yetuReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MansaMusa for YETU allocation. function deposit(uint256 _pid, uint256 _amount) public validatePoolByPid(_pid) { require (_pid != 0, 'deposit YETU by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYetuPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeYetuTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYetuPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MansaMusa. function withdraw(uint256 _pid, uint256 _amount) public validatePoolByPid(_pid) { require (_pid != 0, 'withdraw YETU by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYetuPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeYetuTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accYetuPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake YETU tokens to MansaMusa function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYetuPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeYetuTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYetuPerShare).div(1e12); afrikan.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw YETU tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accYetuPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeYetuTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accYetuPerShare).div(1e12); afrikan.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; uint256 afrikanBalance = afrikan.balanceOf(msg.sender); if (afrikanBalance > 0) afrikan.burn(msg.sender, afrikanBalance); pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe yetu transfer function, just in case if rounding error causes pool to not have enough YETUs. function safeYetuTransfer(address _to, uint256 _amount) internal { afrikan.safeYetuTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(address(_devaddr) != address(0), "Avoid Zero Address"); require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; emit SetDev(msg.sender, _devaddr); } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 yetuReward = multiplier.mul(yetuPerBlock).mul(pool.allocPoint).div(totalAllocPoint); yetu.mint(yetuReward.mul(11).div(10)); yetu.transfer(devaddr, yetuReward.div(10)); yetu.transfer(address(afrikan), yetuReward); pool.accYetuPerShare = pool.accYetuPerShare.add(yetuReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
12,946,827
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelinBase/contracts/access/Ownable.sol"; import "@openzeppelinBase/contracts/GSN/Context.sol"; import "@openzeppelinBase/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelinBase/contracts/token/ERC20/IERC20.sol"; import "@openzeppelinBase/contracts/math/SafeMath.sol"; import "@openzeppelinBase/contracts/math/SignedSafeMath.sol"; import "@openzeppelinBase/contracts/utils/Address.sol"; import "./lib/Math.sol"; import "./lib/Babylonian.sol"; import "./lib/UInt256Lib.sol"; import "./lib/ContractGuard.sol"; import "./lib/Orchestrator.sol"; import "./lib/IBoardroom.sol"; import "./lib/ISimpleERCFund.sol"; import "../interfaces/IRewardsToken.sol"; import "./Epoch.sol"; /** * @title Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */ contract Treasury is ContractGuard, Epoch, Orchestrator { using SafeERC20 for IERC20; using SafeMath for uint256; using UInt256Lib for uint256; using SignedSafeMath for int256; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; // ========== CORE address public fund; address public cash; address public boardroomTimeLock; uint256 public boardroomTimeLockProportion = 70; address public boardroom; uint256 public boardroomProportion = 30; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne = 10**18; uint256 private accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 10; uint256 public IssuanceRatio = 80; uint256 public treasuryReserveRatio = 20; uint256 public timePeriod = 12 hours; int256 public inflationDeflationAmount = 0; /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _seigniorageOracle, address _boardroomTimeLock, address _boardroom, address _fund, uint256 _startTime ) public Epoch(10 minutes, _startTime, 0) { cash = _cash; seigniorageOracle = _seigniorageOracle; boardroomTimeLock = _boardroomTimeLock; boardroom = _boardroom; fund = _fund; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && Operator(boardroomTimeLock).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } // oracle function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash IERC20(cash).safeTransfer(target, IERC20(cash).balanceOf(address(this))); migrated = true; emit Migration(target); } function setFund(address newFund) public onlyOperator { fund = newFund; emit ContributionPoolChanged(msg.sender, newFund); } function setFundAllocationRate(uint256 rate) public onlyOperator { fundAllocationRate = rate; emit ContributionPoolRateChanged(msg.sender, rate); } function setIssuanceRatio(uint256 ratio) public onlyOperator { IssuanceRatio = ratio; } function setTimePeriod(uint256 time) public onlyOperator { timePeriod = time; } /* ========== MUTABLE FUNCTIONS ========== */ function _updateCashPrice() internal { try IOracle(seigniorageOracle).update() {} catch {} } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { // --BIP 1 Supply _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice == cashPriceOne || cashPrice == 0) { inflationDeflationAmount = 0; return; } // circulating supply inflationDeflationAmount = computeSupplyDelta(cashPrice,cashPriceOne); // Price is less than 1 deflation if (cashPrice < cashPriceOne) { IBasisAsset(cash).rebase(epoch,inflationDeflationAmount); externalCall(); IBoardroom(boardroomTimeLock).burnReward(); IBoardroom(boardroom).burnReward(); return; // just advance epoch instead revert } IBoardroom(boardroomTimeLock).setTimeLock(block.timestamp.add(timePeriod)); uint256 seigniorage = uint256(inflationDeflationAmount).mul(IssuanceRatio).div(100); // IssuanceRatio = 50 // --BIP 2 Fund uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); // fundAllocationRate = 10 if (fundReserve > 0) { IRewardsToken(cash).mint(address(this), fundReserve); IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, "Treasury: Seigniorage Allocation" ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // fundAllocationRate out = 90 // --BIP 3 Boardroom if (seigniorage > 0) { IRewardsToken(cash).mint(address(this), seigniorage); // boardroomTimeLock uint256 boardroomTimeSeigniorage = seigniorage.mul(boardroomTimeLockProportion).div(100); // boardroomTimeLockProportion = 70 IERC20(cash).safeApprove(boardroomTimeLock, boardroomTimeSeigniorage); IBoardroom(boardroomTimeLock).allocateSeigniorage(boardroomTimeSeigniorage); // boardroom uint256 boardroomSeigniorage = seigniorage.mul(boardroomProportion).div(100); // boardroomProportion = 30 IERC20(cash).safeApprove(boardroom, boardroomSeigniorage); IBoardroom(boardroom).allocateSeigniorage(boardroomSeigniorage); emit BoardroomFunded(now, seigniorage); } } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) public view returns (int256) { int256 targetRateSigned = targetRate.toInt256Safe(); int256 supply = (IERC20(cash).totalSupply() .sub(IERC20(cash).balanceOf(address(this))) .sub(IERC20(cash).balanceOf(cash))).toInt256Safe(); if(rate < targetRate) { supply = IERC20(cash).totalSupply().toInt256Safe(); } return supply.mul(rate.toInt256Safe().sub(targetRateSigned)). div(targetRateSigned); } function setBoardroomProportion(uint256 _boardroomTimeLockProp,uint256 _boardroomProp) external onlyOperator { boardroomTimeLockProportion = _boardroomTimeLockProp; boardroomProportion = _boardroomProp; } // GOV event Migration(address indexed target); event ContributionPoolChanged(address indexed operator, address newFund); event ContributionPoolRateChanged( address indexed operator, uint256 newRate ); // CORE event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
return Computes the total supply adjustment in response to the exchange rate and the targetRate./
function computeSupplyDelta(uint256 rate, uint256 targetRate) public view returns (int256) { int256 targetRateSigned = targetRate.toInt256Safe(); int256 supply = (IERC20(cash).totalSupply() .sub(IERC20(cash).balanceOf(address(this))) .sub(IERC20(cash).balanceOf(cash))).toInt256Safe(); if(rate < targetRate) { supply = IERC20(cash).totalSupply().toInt256Safe(); } return supply.mul(rate.toInt256Safe().sub(targetRateSigned)). div(targetRateSigned); }
1,798,226
./full_match/5/0x232b57323b4179969DeeA3d85395041040CBF200/sources/contracts/Counter.sol
Function to increment the counter and return the updated value
function incrementCounter() public returns (uint256) { }
1,930,496
./full_match/137/0x78a486306D15E7111cca541F2f1307a1cFCaF5C4/sources/contracts/Peronio.sol
Swap the given amount of tokens from the given "from" address to the given "to" address via QuickSwap, and return the amount of "to" tokens swapped fromAddress Address to get swap tokens from toAddress Address to get swap tokens to amount Amount of tokens to swap (from) return swappedAmount Amount of tokens deposited in addressTo/
function _swapTokens( address fromAddress, address toAddress, uint256 amount ) internal returns (uint256 swappedAmount) { address[] memory path = new address[](2); (path[0], path[1]) = (fromAddress, toAddress); swappedAmount = IUniswapV2Router02(quickSwapRouterAddress).swapExactTokensForTokens(amount, 1, path, address(this), block.timestamp + ONE_HOUR)[1]; }
4,798,463
./full_match/1/0xF41f8965967D645913D0eed58cef2F6C2a7c44Cc/sources/contracts/nft721_contract.sol
Hook that is called after a set of serially-ordered token ids have been transferred. This includes minting. startTokenId - the first token id to be transferred quantity - the amount to be transferred Calling conditions: - when `from` and `to` are both non-zero. - `from` and `to` are never both zero./ Mint Burn
function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal override virtual { require(quantity < 2 ** 64); uint64 _quantity = uint64(quantity); if(from != address(0)){ _addressData[from].balance -= _quantity; _addressData[to].numberMinted += _quantity; } if(to != address(0)){ _addressData[to].balance += _quantity; _addressData[from].numberBurned += _quantity; } super._afterTokenTransfers(from, to, startTokenId, quantity); } bytes32 public constant ADMIN = keccak256("ADMIN");
2,934,810
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract ERC20 { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); //transfers _value to an address _to from msg.sender, returns function transfer(address _to, uint256 _value) internal returns (bool success, string memory message) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return (true, "Transfer Successful"); } return (false, "transfer failed"); } //return the balance of the owner function balanceOf(address _owner) internal view returns (uint256 balance) { return balances[_owner]; } //return total supply of tokens function approve(address _spender, uint256 _value) internal returns (bool success) { allowance[msg.sender][_spender] = _value; //Am setting the approved value or token to give the spender emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) internal returns (bool success) { uint valueToBeTransferred = allowance[_from][_to]; if (balances[_from] >= _value && valueToBeTransferred >= _value && _value > 0){ balances[msg.sender] -= _value; balances[_to] += _value; valueToBeTransferred -= _value; //sometimes the person might not want to remove all the approved cash once!, we go dey comot am small small emit Transfer(msg.sender, _to, _value); return (true); } return false; } //Tells us the balance of the value stored for transfer function checkAllowance(address _owner, address _spender) internal view returns (uint256 remaining) { return allowance[_owner][_spender]; } mapping (address => uint256) balances;// mapping address to a balance mapping (address => mapping (address => uint256)) allowance; uint256 public totalSupply; }
Tells us the balance of the value stored for transfer
function checkAllowance(address _owner, address _spender) internal view returns (uint256 remaining) { return allowance[_owner][_spender]; } mapping (address => mapping (address => uint256)) allowance; uint256 public totalSupply;
12,978,471
pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; //import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt( a.mantissa, scalar ); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt( a.mantissa, b.mantissa ); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt( halfExpScale, doubleScaledProduct ); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } contract CToken { /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } contract getAccountLiquidity is Exponential, ComptrollerErrorReporter { struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } function getHypotheticalAccountLiquidity( address account, CToken[] memory assets, uint256[] memory collateralFactorMantissa, uint256[] memory underlyingPrice ) public view returns ( Error, uint256, uint256, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; MathError mErr; // For each asset the account is in //CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0, 0, 0); } //vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.collateralFactor = Exp({mantissa: collateralFactorMantissa[i]}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset //vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); vars.oraclePriceMantissa = underlyingPrice[i]; if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3( vars.collateralFactor, vars.exchangeRate, vars.oraclePrice ); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt( vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0, 0, 0); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0, vars.sumCollateral, vars.sumBorrowPlusEffects ); } else { return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral, vars.sumCollateral, vars.sumBorrowPlusEffects ); } } }
Multiply an Exp by a scalar, returning a new Exp./
function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { } }
1,271,118
./full_match/10/0xF6a6C4573099E6F6b9D8E1186a2C089B4d0fDf91/sources/home/sol-op/lib/erc20/SafeERC20.sol
bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), '!TRANSFER_FROM_FAILED'); }
3,779,868
pragma solidity ^0.4.24; import "../contracts/ErrorReporter.sol"; import "../contracts/MoneyMarket.sol"; contract MoneyMarketHarness is MoneyMarket { mapping (address => uint) public cashOverrides; mapping (address => bool) accountsToFailLiquidity; mapping (address => Exp) liquidityShortfalls; mapping (address => Exp) liquiditySurpluses; bool public failBorrowDenominatedCollateralCalculation; bool public failCalculateAmountSeize; /** * @dev Mapping of asset addresses and their corresponding price in terms of Eth-Wei * which is simply equal to AssetWeiPrice * 10e18. For instance, if OMG token was * worth 5x Eth then the price for OMG would be 5*10e18 or Exp({mantissa: 5000000000000000000}). * If useOracle is false (its default), then we use this map for prices. * map: assetAddress -> Exp */ mapping (address => Exp) public assetPrices; bool useOracle = false; function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (useOracle) { return super.fetchAssetPrice(asset); } return (Error.NO_ERROR, assetPrices[asset]); } function harnessSetCash(address asset, uint cashAmount) public { cashOverrides[asset] = cashAmount; } function getCash(address asset) internal view returns (uint) { uint override = cashOverrides[asset]; if (override > 0) { return override; } return super.getCash(asset); } function calculateAccountLiquidity(address account) internal view returns (Error, Exp memory, Exp memory) { bool failLiquidityCheck = accountsToFailLiquidity[account]; if (failLiquidityCheck) { return (Error.INTEGER_OVERFLOW, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp storage liquidityShortfall = liquidityShortfalls[account]; if (!isZeroExp(liquidityShortfall)) { return (Error.NO_ERROR, Exp({mantissa: 0}), liquidityShortfall); } Exp storage liquiditySurplus = liquiditySurpluses[account]; if (!isZeroExp(liquiditySurplus)) { return (Error.NO_ERROR, liquiditySurplus, Exp({mantissa: 0})); } return super.calculateAccountLiquidity(account); } function calculateDiscountedBorrowDenominatedCollateral(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint supplyCurrentCollateral) view internal returns (Error, uint) { if (failBorrowDenominatedCollateralCalculation) { return (Error.INTEGER_OVERFLOW, 0); } else { return super.calculateDiscountedBorrowDenominatedCollateral(underwaterAssetPrice, collateralPrice, supplyCurrentCollateral); } } function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint amountCloseOfBorrow) internal view returns (Error, uint) { if (failCalculateAmountSeize) { return (Error.INTEGER_OVERFLOW, 0); } return super.calculateAmountSeize(underwaterAssetPrice, collateralPrice, amountCloseOfBorrow); } // Sets oracle address without checking its validity. function harnessSetOracle(address newOracle) public { oracle = newOracle; } function harnessSetUseOracle(bool _useOracle) public { useOracle = _useOracle; } function harnessSetFailCalculateAmountSeize(bool state) public { failCalculateAmountSeize = state; } function harnessSetFailLiquidityCheck(address account, bool setting) public { accountsToFailLiquidity[account] = setting; } function harnessSetLiquidityShortfall(address account, uint shortfall) public { (Error err0, Exp memory shortfallExp) = getExp(shortfall, 1); assert(err0 == Error.NO_ERROR); liquidityShortfalls[account] = shortfallExp; } function harnessSetLiquiditySurplus(address account, uint surplus) public { (Error err0, Exp memory surplusExp) = getExp(surplus, 1); assert(err0 == Error.NO_ERROR); liquiditySurpluses[account] = surplusExp; } function harnessSetAccountSupplyBalance(address account, address asset, uint principal, uint interestIndex) public { supplyBalances[account][asset] = Balance({ principal: principal, interestIndex: interestIndex }); } function harnessSetAccountBorrowBalance(address account, address asset, uint principal, uint interestIndex) public { borrowBalances[account][asset] = Balance({ principal: principal, interestIndex: interestIndex }); } function harnessSupportMarket(address asset) public { markets[asset].isSupported = true; } function harnessUnsupportMarket(address asset) public { markets[asset].isSupported = false; } function harnessGetSupplyIndex(address asset) public view returns (uint) { return markets[asset].supplyIndex; } function harnessGetBorrowIndex(address asset) public view returns (uint) { return markets[asset].borrowIndex; } function harnessGetInterestRateModel(address asset) public view returns (address) { return markets[asset].interestRateModel; } function harnessSetAssetPrice(address asset, uint priceNum, uint priceDenom) public { (Error err0, Exp memory assetPrice) = getExp(priceNum, priceDenom); assert(err0 == Error.NO_ERROR); setAssetPriceInternal(asset, assetPrice); } function harnessSetAssetPriceMantissa(address asset, uint priceMantissa) public { setAssetPriceInternal(asset, Exp({mantissa: priceMantissa})); } // TODO: RENAME to include harness in name /** * @notice Sets the price of a given asset * @dev Oracle function to set the price of a given asset * @param asset Asset to set the price of * @param assetPriceMantissa Price of asset-wei in terms of eth-wei, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setAssetPrice(address asset, uint assetPriceMantissa) public returns (uint) { // Set the asset price to `price` setAssetPriceInternal(asset, Exp({mantissa: assetPriceMantissa})); return uint(Error.NO_ERROR); } /** * @dev Sets the price for the given asset. The price for any asset must be specified as * the AssetWeiPrice * 10e18. For instance, if DRGN is currently worth 0.00113323 Eth then * the price must be specified as Exp({mantissa: 1133230000000000}). */ function setAssetPriceInternal(address asset, Exp memory price) internal { assetPrices[asset] = price; } function harnessSetMaxAssetPrice(address asset) public { setAssetPriceInternal(asset, Exp({mantissa: 2**256 - 1})); } function harnessSetMarketDetails(address asset, uint totalSupply, uint supplyRateBasisPoints, uint supplyIndex, uint totalBorrows, uint borrowRateBasisPoints, uint borrowIndex) public { (Error err0, Exp memory supplyRate) = getExp(supplyRateBasisPoints, 10000); (Error err1, Exp memory borrowRate) = getExp(borrowRateBasisPoints, 10000); assert(err0 == Error.NO_ERROR); assert(err1 == Error.NO_ERROR); markets[asset].blockNumber = block.number; markets[asset].totalSupply = totalSupply; markets[asset].supplyRateMantissa = supplyRate.mantissa; markets[asset].supplyIndex = supplyIndex; markets[asset].totalBorrows = totalBorrows; markets[asset].borrowRateMantissa = borrowRate.mantissa; markets[asset].borrowIndex = borrowIndex; } function harnessSetAccountSupplyBalanceAndMarketDetails(address account, address asset, uint principal, uint interestIndex, uint totalSupply, uint supplyRateBasisPoints, uint supplyIndex, uint totalBorrows, uint borrowRateBasisPoints, uint borrowIndex) public { harnessSetAccountSupplyBalance(account, asset, principal, interestIndex); harnessSetMarketDetails(asset, totalSupply, supplyRateBasisPoints, supplyIndex, totalBorrows, borrowRateBasisPoints, borrowIndex); } function harnessSetAccountBorrowBalanceAndMarketDetails(address account, address asset, uint principal, uint interestIndex, uint totalSupply, uint supplyRateBasisPoints, uint supplyIndex, uint totalBorrows, uint borrowRateBasisPoints, uint borrowIndex) public { harnessSetAccountBorrowBalance(account, asset, principal, interestIndex); harnessSetMarketDetails(asset, totalSupply, supplyRateBasisPoints, supplyIndex, totalBorrows, borrowRateBasisPoints, borrowIndex); } function harnessSetCollateralRatio(uint ratioNum, uint ratioDenom) public { (Error err0, Exp memory collateralRatioExp) = getExp(ratioNum, ratioDenom); assert(err0 == Error.NO_ERROR); collateralRatio = collateralRatioExp; } function harnessSetMarketBlockNumber(address asset, uint newBlockNumber) public { markets[asset].blockNumber = newBlockNumber; } function harnessSetMarketInterestRateModel(address asset, address interestRateModelAddress) public { markets[asset].interestRateModel = InterestRateModel(interestRateModelAddress); } function harnessCalculateInterestIndex(uint startingInterestIndex, uint interestRateBasisPoints, uint blockDelta) public pure returns (uint) { // TODO: We can probably do this better getExp code in the newer versions of harnesses (Error err0, Exp memory interestRate) = getExp(interestRateBasisPoints, 10000); assert(err0 == Error.NO_ERROR); (Error err1, uint newInterestIndex) = calculateInterestIndex(startingInterestIndex, interestRate.mantissa, 0, blockDelta); assert(err1 == Error.NO_ERROR); return newInterestIndex; } function harnessAddCollateralMarket(address asset) public { addCollateralMarket(asset); } function harnessCalculateAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account); return (uint(err), accountLiquidity.mantissa, accountShortfall.mantissa); } // Lets us set a liquidation discount without any validation or admin controls function harnessSetLiquidationDiscount(uint mantissa) public { liquidationDiscount = Exp({mantissa: mantissa}); } function harnessSetFailBorrowDenominatedCollateralCalculation(bool state) public { failBorrowDenominatedCollateralCalculation = state; } }
TODO: RENAME to include harness in name Sets the price of a given asset Oracle function to set the price of a given asset asset Asset to set the price of assetPriceMantissa Price of asset-wei in terms of eth-wei, scaled by 1e18. return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Set the asset price to `price`
function _setAssetPrice(address asset, uint assetPriceMantissa) public returns (uint) { return uint(Error.NO_ERROR); }
13,089,028
./full_match/1/0x4CaE5458f76Fced0552FDd765DA5200565406841/sources/contracts/MultiVesting.sol
Returns amount of funds that beneficiary can withdraw, vestingId should be specified (default is 0) _beneficiary - address of the beneficiary _vestingId - the ID of the vesting (default is 0)
function getAvailableAmount(address _beneficiary, uint256 _vestingId) public view returns (uint256) { return getAvailableAmountAtTimestamp(_beneficiary, _vestingId, block.timestamp); }
3,861,656
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../interfaces/IStrategy.sol"; import "../interfaces/IVault.sol"; import "../interfaces/IPancakeRouter02.sol"; import "../interfaces/IWaultSwapRouter02.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IWaultPair.sol"; import "../interfaces/INervePair.sol"; import "../interfaces/IWexMaster.sol"; import "../interfaces/IMasterMind.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; contract Strategy is IStrategy, Ownable, Pausable { using SafeBEP20 for IBEP20; using SafeBEP20 for IWaultPair; using SafeBEP20 for INervePair; using SafeMath for uint256; /* ============= CONSTANTS ============= */ IBEP20 private WBNB = IBEP20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); IBEP20 private ETH = IBEP20(0x2170Ed0880ac9A755fd29B2688956BD959F933F8); // Binance Pegged ETH IBEP20 private BETH = IBEP20(0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B); IBEP20 private constant ANYETH = IBEP20(0x6F817a0cE8F7640Add3bC0c1C2298635043c2423); IBEP20 private constant WEX = IBEP20(0xa9c41A46a6B3531d28d5c32F6633dd2fF05dFB90); IBEP20 private constant NRV = IBEP20(0x42F6f551ae042cBe50C739158b4f0CAC0Edb9096); IWaultPair private constant ETH_BETH_LP = IWaultPair(0x11040f3c467993556B19813d4A18b684598Ba4BD); // WaultSwap WETH-BETH LP INervePair private constant ETH_ANYETH_LP = INervePair(0x0d283BF16A9bdE49cfC48d8dc050AF28b71bdD90); // Nerve WETH-anyETH LP IPancakeRouter02 private constant PANCAKE_ROUTER = IPancakeRouter02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // PCS Router V2 IWaultSwapRouter02 private constant WAULT_ROUTER = IWaultSwapRouter02(0xD48745E39BbED146eEC15b79cBF964884F9877c2); // WaultSwap Router ISwap private constant NERVE_SWAP = ISwap(0x146CD24dCc9f4EB224DFd010c5Bf2b0D25aFA9C0); // Nerve ETH-anyETH LP maker IWexMaster private constant WAULT_FARM = IWexMaster(0x22fB2663C7ca71Adc2cc99481C77Aaf21E152e2D); // Wault WETH-BETH Farm, pid = 42 IMasterMind private constant NERVE_FARM = IMasterMind(0x2EBe8CDbCB5fB8564bC45999DAb8DA264E31f24E); // Nerve WETH-anyETH Farm, pid = 5 uint256 private constant WAULT_PID = 42; uint256 private constant NERVE_PID = 5; uint8 private constant ETH_NERVE_TOKEN_ID = 0; uint8 private constant ANYETH_NERVE_TOKEN_ID = 1; uint256 private constant DENOMINATOR = 10000; uint256 private constant MAX_AMT = type(uint256).max; uint256 private constant ONE = 1e18; /* ========== STATE VARIABLES ========== */ // LP token price in ETH uint256 public _price_ETH_BETH_LP; // Might not need uint256 public _price_ETH_ANYETH_LP; // Pool in ETH uint256 public _pool_ETH_BETH_LP; uint256 public _pool_ETH_ANYETH_LP; address public admin; address public communityWallet; address public strategist; IVault public vault; // Farm Allocation Weights uint256 public waultFarmPerc = 5000; // 50% allocation to Wault uint256 public nerveFarmPerc = 5000; // 50% allocation to Nerve // Fees uint256 public yieldFeePerc = 1000; // 10% Yield fees // Information uint256 public totalWaultYield = 0; uint256 public totalNerveYield = 0; /* ============= MODIFIERS ============= */ modifier onlyAdmin { require(msg.sender == address(admin), "Strategy:: Only Admin"); _; } modifier onlyVault { require(msg.sender == address(vault), "Strategy:: Only Vault"); _; } /* ============== EVENTS ============== */ event Invested(uint256 ethInvested); event LiquidityRemoved( address lpToken, uint256 liquidityRemoved, uint256 amountA, uint256 amountB, address router ); event LiquidityAdded( address tokenA, address tokenB, uint256 amountA, uint256 amountB, uint256 liquidity, address router ); event SetVault(address vaultAddress); event SetAdmin(address adminAddress); event SetStrategist(address strategistAddress); event Harvested(uint256 claimedWEX, uint256 claimedNRV); event Withdrawn(uint256 amount, uint256 withdrawalFee); /* ============ CONSTRUCTOR ============ */ constructor( address _communityWallet, address _strategist, address _admin ) public { require( _communityWallet != address(0), "Strategy::constructor: communityWallet does not exist" ); communityWallet = _communityWallet; strategist = _strategist; admin = _admin; ETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); ETH.safeApprove(address(WAULT_ROUTER), MAX_AMT); ETH.safeApprove(address(NERVE_SWAP), MAX_AMT); BETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); BETH.safeApprove(address(WAULT_ROUTER), MAX_AMT); ANYETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); ANYETH.safeApprove(address(NERVE_SWAP), MAX_AMT); ETH_BETH_LP.safeApprove(address(WAULT_FARM), MAX_AMT); ETH_BETH_LP.safeApprove(address(WAULT_ROUTER), MAX_AMT); ETH_ANYETH_LP.safeApprove(address(NERVE_FARM), MAX_AMT); ETH_ANYETH_LP.safeApprove(address(NERVE_SWAP), MAX_AMT); WEX.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); NRV.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); } receive() external payable { // ... } fallback() external { // ... } /* =========== VIEW FUNCTIONS =========== */ /// @notice Get TVL of Strategy in ETH function getStrategyPool() public view override returns (uint256 _valueInEth) { uint256 _valueInEth_ETH_BETH_LP = _pool_ETH_BETH_LP .mul(_calcPriceETH_BETH_LP()) .div(1e18); uint256 _valueInEth_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP .mul(_calcPriceETH_ANYETH_LP()) .div(1e18); _valueInEth = _valueInEth_ETH_BETH_LP.add(_valueInEth_ETH_ANYETH_LP); } /* ========= MUTATIVE FUNCTIONS ========= */ /// @notice Invest tokens into Wault and Nerve Farms /// @param _amount Amount of ETH to invest function invest(uint256 _amount) public override onlyVault whenNotPaused { require(_amount > 0, "Strategy::invest: Invest Amount <= 0"); ETH.safeTransferFrom(address(vault), address(this), _amount); // Divide by 2 to maintain the 1:1 ETH:BETH for LP uint256 _amountToBETH = _amount.mul(waultFarmPerc).div(2).div( DENOMINATOR ); uint256 _amountToANYETH = _amount.mul(nerveFarmPerc).div(2).div( DENOMINATOR ); uint256 _amountRemaining = _amount.sub(_amountToBETH).sub( _amountToANYETH ); uint256 _amountBETH = _swapETHforBETH(_amountToBETH); uint256 _amountANYETH = _swapETHforANYETH(_amountToANYETH); uint256 _amount_ETH_BETH_LP = _addLiquidityWault( _amountRemaining.div(2), _amountBETH ); _amountRemaining = _amountRemaining.sub(_amountRemaining.div(2)); uint256 _amount_ETH_ANYETH_LP = _addLiquidityNerve( _amountRemaining, _amountANYETH ); _investWault(_amount_ETH_BETH_LP); _investNerve(_amount_ETH_ANYETH_LP); // Update Pool uint256 _pool_ETH_BETH_LP_before = _pool_ETH_BETH_LP; (uint256 _pool_ETH_BETH_LP_after, , ) = WAULT_FARM.userInfo( WAULT_PID, address(this) ); uint256 _pool_ETH_ANYETH_LP_before = _pool_ETH_ANYETH_LP; (uint256 _pool_ETH_ANYETH_LP_after, ) = NERVE_FARM.userInfo( NERVE_PID, address(this) ); _pool_ETH_BETH_LP = _pool_ETH_BETH_LP.add( _pool_ETH_BETH_LP_after.sub(_pool_ETH_BETH_LP_before) ); _pool_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP.add( _pool_ETH_ANYETH_LP_after.sub(_pool_ETH_ANYETH_LP_before) ); emit Invested(_amount); } /// @notice Withdraw tokens from farms and swap into ETH /// @dev Liquidate enough LP tokens to meet the amount, 50% from Wault and 50% from Nerve function withdraw(uint256 _amount) public override onlyVault whenNotPaused { require(_amount > 0, "Strategy::withdraw: Withdraw Amount <= 0)"); uint256 _strategyPool = getStrategyPool(); uint256 _amount_ETH_BETH_LP = _amount.mul(_pool_ETH_BETH_LP).div( _strategyPool ); uint256 _amount_ETH_ANYETH_LP = _amount.mul(_pool_ETH_ANYETH_LP).div( _strategyPool ); // Withdrawing automatically harvests yields _withdrawWault(_amount_ETH_BETH_LP); _withdrawNerve(_amount_ETH_ANYETH_LP); ( uint256 _amountETHFromWault, uint256 _amountBETH ) = _removeLiquidityWault(_amount_ETH_BETH_LP); ( uint256 _amountETHFromNerve, uint256 _amountANYETH ) = _removeLiquidityNerve(_amount_ETH_ANYETH_LP); _pool_ETH_BETH_LP = _pool_ETH_BETH_LP.sub(_amount_ETH_BETH_LP); _pool_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP.sub(_amount_ETH_ANYETH_LP); uint256 _totalRewards = _liquidateRewards(); // in ETH uint256 _fees = _totalRewards.mul(yieldFeePerc).div(DENOMINATOR); _splitYieldFees(_fees); // Swap BETH and anyETH back to ETH uint256 _amountETHFromBETH = _swapBETHforETH(_amountBETH); uint256 _amountETHFromANYETH = _swapANYETHforETH(_amountANYETH); uint256 _amountETH = _amountETHFromWault.add(_amountETHFromNerve).add( _totalRewards ); _amountETH = _amountETH.sub(_fees).add(_amountETHFromBETH).add( _amountETHFromANYETH ); // Send deserved ETH back to Vault ETH.safeTransfer(address(vault), _amountETH); } /// @notice Harvest yields from farms and reinvest them function compound() external override onlyVault whenNotPaused { _harvest(); uint256 _amount = _liquidateRewards(); invest(_amount); } /* ========= PRIVATE FUNCTIONS ========= */ /// @notice Invest ETH-BETH LP tokens into WexMaster function _investWault(uint256 _amount) private { require( _amount > 0, "Strategy::_investWault: Invalid Amount (_amount <= 0)" ); WAULT_FARM.deposit(WAULT_PID, _amount, false); } /// @notice Invest ETH-anyETH LP tokens into MasterMind function _investNerve(uint256 _amount) private { require( _amount > 0, "Strategy::_investNerve: Invalid Amount (_amount <= 0)" ); NERVE_FARM.deposit(NERVE_PID, _amount); } /// @notice Withdraw ETH-BETH LP Tokens from WexMaster function _withdrawWault(uint256 _amount) private { WAULT_FARM.withdraw(WAULT_PID, _amount, true); } /// @notice Withdraw ETH-anyETH LP Tokens from MasterMind function _withdrawNerve(uint256 _amount) private { NERVE_FARM.withdraw(NERVE_PID, _amount); } /// @notice Harvest yields from farms function _harvest() private { uint256 _claimedWEX = _harvestWault(); uint256 _claimedNRV = _harvestNerve(); totalWaultYield = totalWaultYield.add(_claimedWEX); totalNerveYield = totalNerveYield.add(_claimedNRV); emit Harvested(_claimedWEX, _claimedNRV); } /// @notice Harvest Wault Rewards function _harvestWault() private returns (uint256 _rewardsClaimed) { uint256 _pendingRewards = WAULT_FARM.pendingWex( WAULT_PID, address(this) ); _rewardsClaimed = 0; // Check if pending WEX is above 0 if (_pendingRewards > 0) { WAULT_FARM.claim(WAULT_PID); _rewardsClaimed = _pendingRewards; } } /// @notice Harvest Nerve Rewards function _harvestNerve() private returns (uint256 _rewardsClaimed) { uint256 _pendingRewards = NERVE_FARM.pendingNerve( NERVE_PID, address(this) ); _rewardsClaimed = 0; // Check if pending NRV is above 0 // TODO: Write logic to claim NRV rewards, Nerve Finance locks up 2/3 rewards and does not have claim function if (_pendingRewards > 0) { NERVE_FARM.withdraw(NERVE_PID, 0); _rewardsClaimed = _pendingRewards; } } /// @notice Swaps ETH for BETH on Pancake Router function _swapETHforBETH(uint256 _amount) private returns (uint256 _amountBETH) { uint256[] memory _amounts = _swapExactTokensForTokens( address(ETH), address(BETH), _amount ); _amountBETH = _amounts[1]; } /// @notice Swaps ETH for anyETH on Pancake Router function _swapETHforANYETH(uint256 _amount) private returns (uint256 _amountANYETH) { // Only nerveswap has liquidity uint256 _amountsOut = NERVE_SWAP.calculateSwap( ETH_NERVE_TOKEN_ID, ANYETH_NERVE_TOKEN_ID, _amount ); if (_amountsOut > 0) { _amountANYETH = NERVE_SWAP.swap( ETH_NERVE_TOKEN_ID, ANYETH_NERVE_TOKEN_ID, _amount, 0, block.timestamp ); } else { // Not enough amount to swap _amountANYETH = 0; } } /// @notice Swaps BETH for ETH on Pancake Router function _swapBETHforETH(uint256 _amount) private returns (uint256 _amountETH) { uint256[] memory _amounts = _swapExactTokensForTokens( address(BETH), address(ETH), _amount ); _amountETH = _amounts[1]; } /// @notice Swaps ANYETH for ETH on Pancake Router function _swapANYETHforETH(uint256 _amount) private returns (uint256 _amountETH) { // Only nerveswap has liquidity uint256 _amountsOut = NERVE_SWAP.calculateSwap( ANYETH_NERVE_TOKEN_ID, ETH_NERVE_TOKEN_ID, _amount ); if (_amountsOut > 0) { _amountETH = NERVE_SWAP.swap( ANYETH_NERVE_TOKEN_ID, ETH_NERVE_TOKEN_ID, _amount, 0, block.timestamp ); } else { // Not enough amount to swap _amountETH = 0; } } /// @notice Get Wault ETH-BETH LP tokens function _addLiquidityWault(uint256 _amountETH, uint256 _amountBETH) private returns (uint256) { (uint256 _amountA, uint256 _amountB, uint256 _liquidity) = WAULT_ROUTER .addLiquidity( address(ETH), address(BETH), _amountETH, _amountBETH, 0, 0, address(this), block.timestamp ); emit LiquidityAdded( address(ETH), address(BETH), _amountA, _amountB, _liquidity, address(WAULT_ROUTER) ); return _liquidity; } /// @notice Get Nerve ETH-anyETH LP tokens function _addLiquidityNerve(uint256 _amountETH, uint256 _amountANYETH) private returns (uint256 _liquidity) { uint256[] memory _amounts = new uint256[](2); _amounts[0] = _amountETH; _amounts[1] = _amountANYETH; _liquidity = NERVE_SWAP.addLiquidity(_amounts, 0, block.timestamp); emit LiquidityAdded( address(ETH), address(ANYETH), _amountETH, _amountANYETH, _liquidity, address(NERVE_SWAP) ); } /// @notice Remove ETH-BETH Liquidity from Wault Swap function _removeLiquidityWault(uint256 _amount) private returns (uint256 _amountA, uint256 _amountB) { (_amountA, _amountB) = WAULT_ROUTER.removeLiquidity( address(ETH), address(BETH), _amount, 0, 0, address(this), block.timestamp ); emit LiquidityRemoved( address(ETH_BETH_LP), _amount, _amountA, _amountB, address(WAULT_ROUTER) ); } /// @notice Remove ETH-anyETH Liquidity from Nerve Swap function _removeLiquidityNerve(uint256 _amount) private returns (uint256 _amountA, uint256 _amountB) { uint256[] memory _minAmounts = new uint256[](2); _minAmounts[0] = 0; _minAmounts[1] = 0; uint256[] memory _returnedAmounts = NERVE_SWAP.removeLiquidity( _amount, _minAmounts, block.timestamp ); _amountA = _returnedAmounts[0]; _amountB = _returnedAmounts[1]; emit LiquidityRemoved( address(ETH_ANYETH_LP), _amount, _amountA, _amountB, address(NERVE_SWAP) ); } /// @notice Convert all rewards (WEX + NRV) into base token (ETH) function _liquidateRewards() private returns (uint256 _totalRewards) { // Liquidate Wault Rewards uint256 _waultRewards = _liquidateWaultRewards(); // Liquidate Nerve Rewards uint256 _nerveRewards = _liquidateNerveRewards(); // Calculate total ETH gained from rewards _totalRewards = _waultRewards.add(_nerveRewards); } /// @notice Function to transfer fees that collect from yield to wallets /// @param _amount Fees to transfer in ETH Token function _splitYieldFees(uint256 _amount) private { uint256 _creditToAdmin = (_amount).mul(2).div(5); uint256 _creditToCommunityWallet = (_amount).mul(2).div(5); uint256 _creditToStrategist = (_amount).mul(1).div(5); ETH.safeTransfer(admin, _creditToAdmin); // 40% ETH.safeTransfer(communityWallet, _creditToCommunityWallet); // 40% ETH.safeTransfer(strategist, _creditToStrategist); // 20% } /// @notice Converts WEX rewards to ETH function _liquidateWaultRewards() private returns (uint256 _yieldAmount) { uint256 _balanceOfWEX = WEX.balanceOf(address(this)); _yieldAmount = 0; if (_balanceOfWEX > 0) { uint256[] memory _amounts = _swapExactTokensForTokens2( address(WEX), address(ETH), _balanceOfWEX ); _yieldAmount = _amounts[2]; } } /// @notice Converts NRV rewards to ETH function _liquidateNerveRewards() private returns (uint256 _yieldAmount) { uint256 _balanceOfNRV = NRV.balanceOf(address(this)); _yieldAmount = 0; if (_balanceOfNRV > 0) { uint256[] memory _amounts = _swapExactTokensForTokens2( address(NRV), address(ETH), _balanceOfNRV ); _yieldAmount = _amounts[2]; } } /// @notice Function to swap tokens with PancakeSwap /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @param _amountIn Amount of token to be swapped /// @return _amounts Array that contains swapped amounts function _swapExactTokensForTokens( address _tokenA, address _tokenB, uint256 _amountIn ) private returns (uint256[] memory _amounts) { address[] memory _path = _getPath(_tokenA, _tokenB); uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut( _amountIn, _path ); if (_amountsOut[1] > 0) { _amounts = PANCAKE_ROUTER.swapExactTokensForTokens( _amountIn, 0, _path, address(this), block.timestamp ); } else { // Not enough amount to swap uint256[] memory _zeroReturn = new uint256[](2); _zeroReturn[0] = 0; _zeroReturn[1] = 0; return _zeroReturn; } } /// @notice Function to swap Exotic tokens with PancakeSwap /// @dev For tokens that cannot be swapped directly /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @param _amountIn Amount of token to be swapped /// @return _amounts Array that contains swapped amounts function _swapExactTokensForTokens2( address _tokenA, address _tokenB, uint256 _amountIn ) private returns (uint256[] memory _amounts) { address[] memory _path = _getPath2(_tokenA, _tokenB); uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut( _amountIn, _path ); if (_amountsOut[2] > 0) { _amounts = PANCAKE_ROUTER.swapExactTokensForTokens( _amountIn, 0, _path, address(this), block.timestamp ); } else { // Not enough amount to swap uint256[] memory _zeroReturn = new uint256[](2); _zeroReturn[0] = 0; _zeroReturn[2] = 0; return _zeroReturn; } } /// @notice Function to get path for PancakeSwap swap functions /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @return _path Array of address function _getPath(address _tokenA, address _tokenB) private pure returns (address[] memory) { address[] memory _path = new address[](2); _path[0] = _tokenA; _path[1] = _tokenB; return _path; } /// @notice Function to get path for PancakeSwap swap functions, for exotic tokens /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @return _path Array of address with WBNB in between function _getPath2(address _tokenA, address _tokenB) private view returns (address[] memory) { address[] memory _path = new address[](3); _path[0] = _tokenA; _path[1] = address(WBNB); _path[2] = _tokenB; return _path; } /// @notice Calculate price of 1 ETH-BETH LP in ETH function _calcPriceETH_BETH_LP() public view override returns (uint256 _valueInEth) { uint256 _totalSupply = ETH_BETH_LP.totalSupply(); (uint256 _amountETH, uint256 _amountBETH, ) = ETH_BETH_LP.getReserves(); address[] memory _path = _getPath(address(BETH), address(ETH)); uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut(ONE, _path); uint256 _priceBETH = _amountsOut[1]; uint256 _valueBETH = _amountBETH.mul(_priceBETH).div(1e18); uint256 _totalAmount = _amountETH.add(_valueBETH); _valueInEth = _totalAmount.mul(1e18).div(_totalSupply); } /// @notice Calculate price of 1 ETH-anyETH LP in ETH function _calcPriceETH_ANYETH_LP() public view override returns (uint256 _valueInEth) { _valueInEth = NERVE_SWAP.getVirtualPrice(); // 1e18 } /* ========== ADMIN FUNCTIONS ========== */ /// @notice Function to set new admin address from vault contract /// @dev Only can set Once /// @param _address Address of Vault function setVault(address _address) external onlyOwner { require( address(vault) == address(0), "Strategy::setVault:Vault already set" ); vault = IVault(_address); emit SetVault(_address); } /// @notice Function to set new admin address from vault contract /// @param _address Address of new admin function setAdmin(address _address) external override onlyVault { admin = _address; emit SetAdmin(_address); } /// @notice Function to set new strategist address from vault contract /// @param _address Address of new strategist function setStrategist(address _address) external override onlyVault { strategist = _address; emit SetStrategist(_address); } /// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms function reimburse() external override onlyVault { // Get total reimburse amount (6 decimals) uint256 _reimburseAmount = vault.getMinimumKeep(); withdraw(_reimburseAmount); } /// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms function emergencyWithdraw() external override onlyVault whenNotPaused { (uint256 _amount_ETH_BETH_LP, , ) = WAULT_FARM.userInfo( WAULT_PID, address(this) ); (uint256 _amount_ETH_ANYETH_LP, ) = NERVE_FARM.userInfo( NERVE_PID, address(this) ); // Withdrawing automatically harvests yields _withdrawWault(_amount_ETH_BETH_LP); _withdrawNerve(_amount_ETH_ANYETH_LP); ( uint256 _amountETHFromWault, uint256 _amountBETH ) = _removeLiquidityWault(_amount_ETH_BETH_LP); ( uint256 _amountETHFromNerve, uint256 _amountANYETH ) = _removeLiquidityNerve(_amount_ETH_ANYETH_LP); uint256 _totalRewards = _liquidateRewards(); // in ETH uint256 _fees = _totalRewards.mul(yieldFeePerc).div(DENOMINATOR); _splitYieldFees(_fees); // Swap BETH and anyETH back to ETH uint256 _amountETHFromBETH = _swapBETHforETH(_amountBETH); uint256 _amountETHFromANYETH = _swapANYETHforETH(_amountANYETH); uint256 _amountETH = __calcETH( _amountETHFromWault, _amountETHFromNerve, _totalRewards, _fees, _amountETHFromBETH, _amountETHFromANYETH ); // Send deserved ETH back to Vault ETH.safeTransfer(address(vault), _amountETH); _pause(); } function __calcETH( uint256 a, uint256 b, uint256 c, uint256 d, uint256 e, uint256 f ) private pure returns (uint256 _amountETH) { _amountETH = a.add(b).add(c).sub(d).add(e); _amountETH = _amountETH.add(f); } /// @notice Function to invest back WETH into farms after emergencyWithdraw() function reinvest() external override onlyVault whenPaused { _unpause(); } }
Swaps BETH for ETH on Pancake Router
function _swapBETHforETH(uint256 _amount) private returns (uint256 _amountETH) { uint256[] memory _amounts = _swapExactTokensForTokens( address(BETH), address(ETH), _amount ); _amountETH = _amounts[1]; }
6,472,809
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ShackledStructs.sol"; import "./ShackledRenderer.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract ShackledIcons is ERC721Enumerable, Ownable { string public currentBaseURI; mapping(uint256 => bytes32) public tokenHashes; constructor() ERC721("ShackledIcons", "ICON") {} /** * @dev Mint token ids to a particular address */ function mint(address to, uint256 tokenId) public onlyOwner { require( tokenHashes[tokenId] != 0x0, "Cannot mint a token that doesn't exist" ); _safeMint(to, tokenId); } function storeTokenHash(uint256 tokenId, bytes32 tokenHash) public onlyOwner { tokenHashes[tokenId] = tokenHash; } function getRenderParamsHash( ShackledStructs.RenderParams calldata renderParams ) public pure returns (bytes32) { return keccak256( abi.encodePacked( abi.encodePacked( renderParams.faces, renderParams.verts, renderParams.cols ), abi.encodePacked( renderParams.objPosition, renderParams.objScale, renderParams.backgroundColor, renderParams.perspCamera, renderParams.backfaceCulling, renderParams.invert, renderParams.wireframe ), _getLightingParamsHash(renderParams.lightingParams) ) ); } function _getLightingParamsHash( ShackledStructs.LightingParams calldata lightingParams ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( lightingParams.applyLighting, lightingParams.lightAmbiPower, lightingParams.lightDiffPower, lightingParams.lightSpecPower, lightingParams.inverseShininess, lightingParams.lightPos, lightingParams.lightColSpec, lightingParams.lightColDiff, lightingParams.lightColAmbi ) ); } function render( uint256 tokenId, int256 canvasDim_, ShackledStructs.RenderParams calldata renderParams ) public view returns (string memory) { bytes32 tokenHash = getRenderParamsHash(renderParams); require(tokenHash == tokenHashes[tokenId], "Token hash mismatch"); return ShackledRenderer.render(renderParams, canvasDim_, true); } function setBaseURI(string memory baseURI_) public onlyOwner { currentBaseURI = baseURI_; } function _baseURI() internal view virtual override returns (string memory) { return currentBaseURI; } } // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library ShackledStructs { struct Metadata { string colorScheme; /// name of the color scheme string geomSpec; /// name of the geometry specification uint256 nPrisms; /// number of prisms made string pseudoSymmetry; /// horizontal, vertical, diagonal string wireframe; /// enabled or disabled string inversion; /// enabled or disabled } struct RenderParams { uint256[3][] faces; /// index of verts and colorss used for each face (triangle) int256[3][] verts; /// x, y, z coordinates used in the geometry int256[3][] cols; /// colors of each vert int256[3] objPosition; /// position to place the object int256 objScale; /// scalar for the object int256[3][2] backgroundColor; /// color of the background (gradient) LightingParams lightingParams; /// parameters for the lighting bool perspCamera; /// true = perspective camera, false = orthographic bool backfaceCulling; /// whether to implement backface culling (saves gas!) bool invert; /// whether to invert colors in the final encoding stage bool wireframe; /// whether to only render edges } /// struct for testing lighting struct LightingParams { bool applyLighting; /// true = apply lighting, false = don't apply lighting int256 lightAmbiPower; /// power of the ambient light int256 lightDiffPower; /// power of the diffuse light int256 lightSpecPower; /// power of the specular light uint256 inverseShininess; /// shininess of the material int256[3] lightPos; /// position of the light int256[3] lightColSpec; /// color of the specular light int256[3] lightColDiff; /// color of the diffuse light int256[3] lightColAmbi; /// color of the ambient light } } // // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledCoords.sol"; import "./ShackledRasteriser.sol"; import "./ShackledUtils.sol"; import "./ShackledStructs.sol"; library ShackledRenderer { uint256 constant outputHeight = 512; uint256 constant outputWidth = 512; /** @dev take any geometry, render it, and return a bitmap image inside an SVG this can be called to render the Shackled art collection (the output of ShackledGenesis.sol) or any other custom made geometry */ function render( ShackledStructs.RenderParams memory renderParams, int256 canvasDim, bool returnSVG ) public view returns (string memory) { /// prepare the fragments int256[12][3][] memory trisFragments = prepareGeometryForRender( renderParams, canvasDim ); /// run Bresenham's line algorithm to rasterize the fragments int256[12][] memory fragments = ShackledRasteriser.rasterise( trisFragments, canvasDim, renderParams.wireframe ); fragments = ShackledRasteriser.depthTesting(fragments, canvasDim); if (renderParams.lightingParams.applyLighting) { /// apply lighting (Blinn phong) fragments = ShackledRasteriser.lightScene( fragments, renderParams.lightingParams ); } /// get the background int256[5][] memory background = ShackledRasteriser.getBackground( canvasDim, renderParams.backgroundColor ); /// place each fragment in an encoded bitmap string memory encodedBitmap = ShackledUtils.getEncodedBitmap( fragments, background, canvasDim, renderParams.invert ); if (returnSVG) { /// insert the bitmap into an encoded svg (to be accepted by OpenSea) return ShackledUtils.getSVGContainer( encodedBitmap, canvasDim, outputHeight, outputWidth ); } else { return encodedBitmap; } } /** @dev prepare the triangles and colors for rasterization */ function prepareGeometryForRender( ShackledStructs.RenderParams memory renderParams, int256 canvasDim ) internal view returns (int256[12][3][] memory) { /// convert geometry and colors from PLY standard into Shackled format /// create the final triangles and colors that will be rendered /// by pulling the numbers out of the faces array /// and using them to index into the verts and colors arrays /// make copies of each coordinate and color int256[3][3][] memory tris = new int256[3][3][]( renderParams.faces.length ); int256[3][3][] memory trisCols = new int256[3][3][]( renderParams.faces.length ); for (uint256 i = 0; i < renderParams.faces.length; i++) { for (uint256 j = 0; j < 3; j++) { for (uint256 k = 0; k < 3; k++) { /// copy the values from verts and cols arrays /// using the faces lookup array to index into them tris[i][j][k] = renderParams.verts[ renderParams.faces[i][j] ][k]; trisCols[i][j][k] = renderParams.cols[ renderParams.faces[i][j] ][k]; } } } /// convert the fragments from model to world space int256[3][] memory vertsWorldSpace = ShackledCoords .convertToWorldSpaceWithModelTransform( tris, renderParams.objScale, renderParams.objPosition ); /// convert the vertices back to triangles in world space int256[3][3][] memory trisWorldSpace = ShackledUtils .unflattenVertsToTris(vertsWorldSpace); /// implement backface culling if (renderParams.backfaceCulling) { (trisWorldSpace, trisCols) = ShackledCoords.backfaceCulling( trisWorldSpace, trisCols ); } /// update vertsWorldSpace vertsWorldSpace = ShackledUtils.flattenTris(trisWorldSpace); /// convert the fragments from world to camera space int256[3][] memory vertsCameraSpace = ShackledCoords .convertToCameraSpaceViaVertexShader( vertsWorldSpace, canvasDim, renderParams.perspCamera ); /// convert the vertices back to triangles in camera space int256[3][3][] memory trisCameraSpace = ShackledUtils .unflattenVertsToTris(vertsCameraSpace); int256[12][3][] memory trisFragments = ShackledRasteriser .initialiseFragments( trisCameraSpace, trisWorldSpace, trisCols, canvasDim ); return trisFragments; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/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: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledUtils.sol"; import "./ShackledMath.sol"; library ShackledCoords { /** @dev scale and translate the verts this can be effectively disabled with a scale of 1 and translate of [0, 0, 0] */ function convertToWorldSpaceWithModelTransform( int256[3][3][] memory tris, int256 scale, int256[3] memory position ) external view returns (int256[3][] memory) { int256[3][] memory verts = ShackledUtils.flattenTris(tris); // Scale model matrices are easy, just multiply through by the scale value int256[3][] memory scaledVerts = new int256[3][](verts.length); for (uint256 i = 0; i < verts.length; i++) { scaledVerts[i][0] = verts[i][0] * scale + position[0]; scaledVerts[i][1] = verts[i][1] * scale + position[1]; scaledVerts[i][2] = verts[i][2] * scale + position[2]; } return scaledVerts; } /** @dev run backfaceCulling to save future operations on faces that aren't seen by the camera*/ function backfaceCulling( int256[3][3][] memory trisWorldSpace, int256[3][3][] memory trisCols ) external view returns ( int256[3][3][] memory culledTrisWorldSpace, int256[3][3][] memory culledTrisCols ) { culledTrisWorldSpace = new int256[3][3][](trisWorldSpace.length); culledTrisCols = new int256[3][3][](trisCols.length); uint256 nextIx; for (uint256 i = 0; i < trisWorldSpace.length; i++) { int256[3] memory v1 = trisWorldSpace[i][0]; int256[3] memory v2 = trisWorldSpace[i][1]; int256[3] memory v3 = trisWorldSpace[i][2]; int256[3] memory norm = ShackledMath.crossProduct( ShackledMath.vector3Sub(v1, v2), ShackledMath.vector3Sub(v2, v3) ); /// since shackled has a static positioned camera at the origin, /// the points are already in view space, relaxing the backfaceCullingCond int256 backfaceCullingCond = ShackledMath.vector3Dot(v1, norm); if (backfaceCullingCond < 0) { culledTrisWorldSpace[nextIx] = trisWorldSpace[i]; culledTrisCols[nextIx] = trisCols[i]; nextIx++; } } /// remove any empty slots uint256 nToCull = culledTrisWorldSpace.length - nextIx; /// cull uneeded tris assembly { mstore( culledTrisWorldSpace, sub(mload(culledTrisWorldSpace), nToCull) ) } /// cull uneeded cols assembly { mstore(culledTrisCols, sub(mload(culledTrisCols), nToCull)) } } /**@dev calculate verts in camera space */ function convertToCameraSpaceViaVertexShader( int256[3][] memory vertsWorldSpace, int256 canvasDim, bool perspCamera ) external view returns (int256[3][] memory) { // get the camera matrix as a numerator and denominator int256[4][4][2] memory cameraMatrix; if (perspCamera) { cameraMatrix = getCameraMatrixPersp(); } else { cameraMatrix = getCameraMatrixOrth(canvasDim); } int256[4][4] memory nM = cameraMatrix[0]; // camera matrix numerator int256[4][4] memory dM = cameraMatrix[1]; // camera matrix denominator int256[3][] memory verticesCameraSpace = new int256[3][]( vertsWorldSpace.length ); for (uint256 i = 0; i < vertsWorldSpace.length; i++) { // Convert from 3D to 4D homogenous coordinate system int256[3] memory vert = vertsWorldSpace[i]; // Make a copy of vert ("homoVertex") int256[] memory hv = new int256[](vert.length + 1); for (uint256 j = 0; j < vert.length; j++) { hv[j] = vert[j]; } // Insert 1 at final position in copy of vert hv[hv.length - 1] = 1; int256 x = ((hv[0] * nM[0][0]) / dM[0][0]) + ((hv[1] * nM[0][1]) / dM[0][1]) + ((hv[2] * nM[0][2]) / dM[0][2]) + (nM[0][3] / dM[0][3]); int256 y = ((hv[0] * nM[1][0]) / dM[1][0]) + ((hv[1] * nM[1][1]) / dM[1][1]) + ((hv[2] * nM[1][2]) / dM[1][2]) + (nM[1][3] / dM[1][0]); int256 z = ((hv[0] * nM[2][0]) / dM[2][0]) + ((hv[1] * nM[2][1]) / dM[2][1]) + ((hv[2] * nM[2][2]) / dM[2][2]) + (nM[2][3] / dM[2][3]); int256 w = ((hv[0] * nM[3][0]) / dM[3][0]) + ((hv[1] * nM[3][1]) / dM[3][1]) + ((hv[2] * nM[3][2]) / dM[3][2]) + (nM[3][3] / dM[3][3]); if (w != 1) { x = (x * 1e3) / w; y = (y * 1e3) / w; z = (z * 1e3) / w; } // Turn it back into a 3-vector // Add it to the ordered list verticesCameraSpace[i] = [x, y, z]; } return verticesCameraSpace; } /** @dev generate an orthographic camera matrix */ function getCameraMatrixOrth(int256 canvasDim) internal pure returns (int256[4][4][2] memory) { int256 canvasHalf = canvasDim / 2; // Left, right, top, bottom int256 r = ShackledMath.abs(canvasHalf); int256 l = -canvasHalf; int256 t = ShackledMath.abs(canvasHalf); int256 b = -canvasHalf; // Z settings (near and far) /// multiplied by 1e3 int256 n = 1; int256 f = 1024; // Get the orthographic transform matrix // as a numerator and denominator int256[4][4] memory cameraMatrixNum = [ [int256(2), 0, 0, -(r + l)], [int256(0), 2, 0, -(t + b)], [int256(0), 0, -2, -(f + n)], [int256(0), 0, 0, 1] ]; int256[4][4] memory cameraMatrixDen = [ [int256(r - l), 1, 1, (r - l)], [int256(1), (t - b), 1, (t - b)], [int256(1), 1, (f - n), (f - n)], [int256(1), 1, 1, 1] ]; int256[4][4][2] memory cameraMatrix = [ cameraMatrixNum, cameraMatrixDen ]; return cameraMatrix; } /** @dev generate a perspective camera matrix */ function getCameraMatrixPersp() internal pure returns (int256[4][4][2] memory) { // Z settings (near and far) /// multiplied by 1e3 int256 n = 500; int256 f = 501; // Get the perspective transform matrix // as a numerator and denominator // parameter = 1 / tan(fov in degrees / 2) // 0.1763 = 1 / tan(160 / 2) // 1.428 = 1 / tan(70 / 2) // 1.732 = 1 / tan(60 / 2) // 2.145 = 1 / tan(50 / 2) int256[4][4] memory cameraMatrixNum = [ [int256(2145), 0, 0, 0], [int256(0), 2145, 0, 0], [int256(0), 0, f, -f * n], [int256(0), 0, 1, 0] ]; int256[4][4] memory cameraMatrixDen = [ [int256(1000), 1, 1, 1], [int256(1), 1000, 1, 1], [int256(1), 1, f - n, f - n], [int256(1), 1, 1, 1] ]; int256[4][4][2] memory cameraMatrix = [ cameraMatrixNum, cameraMatrixDen ]; return cameraMatrix; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledUtils.sol"; import "./ShackledMath.sol"; import "./ShackledStructs.sol"; library ShackledRasteriser { /// define some constant lighting parameters int256 constant fidelity = int256(100); /// an extra paramater to improve numeric resolution int256 constant lightAmbiPower = int256(1); // Base light colour // was 0.5 int256 constant lightDiffPower = int256(3e9); // Diffused light on surface relative strength int256 constant lightSpecPower = int256(1e7); // Specular reflection on surface relative strength uint256 constant inverseShininess = 10; // 'sharpness' of specular light on surface /// define a scale factor to use in lerp to avoid rounding errors int256 constant lerpScaleFactor = 1e3; /// storing variables used in the fragment lighting struct LightingVars { int256[3] fragCol; int256[3] fragNorm; int256[3] fragPos; int256[3] V; int256 vMag; int256[3] N; int256 nMag; int256[3] L; int256 lMag; int256 falloff; int256 lnDot; int256 lambertian; } /// store variables used in Bresenham's line algorithm struct BresenhamsVars { int256 x; int256 y; int256 dx; int256 dy; int256 sx; int256 sy; int256 err; int256 e2; } /// store variables used when running the scanline algorithm struct ScanlineVars { int256 left; int256 right; int256[12] leftFrag; int256[12] rightFrag; int256 dx; int256 ir; int256 newFragRow; int256 newFragCol; } /** @dev initialise the fragments fragments are defined as: [ canvas_x, canvas_y, depth, col_x, col_y, col_z, normal_x, normal_y, normal_z, world_x, world_y, world_z ] */ function initialiseFragments( int256[3][3][] memory trisCameraSpace, int256[3][3][] memory trisWorldSpace, int256[3][3][] memory trisCols, int256 canvasDim ) external view returns (int256[12][3][] memory) { /// make an array containing the fragments of each triangle (groups of 3 frags) int256[12][3][] memory trisFragments = new int256[12][3][]( trisCameraSpace.length ); // First convert from camera space to screen space within each triangle for (uint256 t = 0; t < trisCameraSpace.length; t++) { int256[3][3] memory tri = trisCameraSpace[t]; /// initialise an array for three fragments, each of len 9 int256[12][3] memory triFragments; // First calculate the fragments that belong to defined vertices for (uint256 v = 0; v < 3; v++) { int256[12] memory fragment; // first convert to screen space // mapping from -1e3 -> 1e3 to account for the original geom being on order of 1e3 fragment[0] = ShackledMath.mapRangeToRange( tri[v][0], -1e3, 1e3, 0, canvasDim ); fragment[1] = ShackledMath.mapRangeToRange( tri[v][1], -1e3, 1e3, 0, canvasDim ); fragment[2] = tri[v][2]; // Now calculate the normal using the cross product of the edge vectors. This needs to be // done in world space coordinates int256[3] memory thisV = trisWorldSpace[t][(v + 0) % 3]; int256[3] memory nextV = trisWorldSpace[t][(v + 1) % 3]; int256[3] memory prevV = trisWorldSpace[t][(v + 2) % 3]; int256[3] memory norm = ShackledMath.crossProduct( ShackledMath.vector3Sub(prevV, thisV), ShackledMath.vector3Sub(thisV, nextV) ); // Now attach the colour (in 0 -> 255 space) fragment[3] = (trisCols[t][v][0]); fragment[4] = (trisCols[t][v][1]); fragment[5] = (trisCols[t][v][2]); // And the normal (inverted) fragment[6] = -norm[0]; fragment[7] = -norm[1]; fragment[8] = -norm[2]; // And the world position of this vertex to the frag fragment[9] = thisV[0]; fragment[10] = thisV[1]; fragment[11] = thisV[2]; // These are just the fragments attached to // the given vertices triFragments[v] = fragment; } trisFragments[t] = triFragments; } return trisFragments; } /** @dev rasterize fragments onto a canvas */ function rasterise( int256[12][3][] memory trisFragments, int256 canvasDim, bool wireframe ) external view returns (int256[12][] memory) { /// determine the upper limits of the inner Bresenham's result uint256 canvasHypot = uint256(ShackledMath.hypot(canvasDim, canvasDim)); /// initialise a new array /// for each trisFragments we will get 3 results from bresenhams /// maximum of 1 per pixel (canvasDim**2) int256[12][] memory fragments = new int256[12][]( 3 * uint256(canvasDim)**2 ); uint256 nextFragmentsIx = 0; for (uint256 t = 0; t < trisFragments.length; t++) { // prepare the variables required int256[12] memory fa; int256[12] memory fb; uint256 nextBresTriFragmentIx = 0; /// create an array to hold the bresenham results /// this may cause an out of bounds error if there are a very large number of fragments /// (e.g. many that are 'off screen') int256[12][] memory bresTriFragments = new int256[12][]( canvasHypot * 10 ); // for each pair of fragments, run bresenhams and extend bresTriFragments with the output // this replaces the three push(...modified_bresenhams_algorhtm) statements in JS for (uint256 i = 0; i < 3; i++) { if (i == 0) { fa = trisFragments[t][0]; fb = trisFragments[t][1]; } else if (i == 1) { fa = trisFragments[t][1]; fb = trisFragments[t][2]; } else { fa = trisFragments[t][2]; fb = trisFragments[t][0]; } // run the bresenhams algorithm ( bresTriFragments, nextBresTriFragmentIx ) = runBresenhamsAlgorithm( fa, fb, canvasDim, bresTriFragments, nextBresTriFragmentIx ); } bresTriFragments = ShackledUtils.clipArray12ToLength( bresTriFragments, nextBresTriFragmentIx ); if (wireframe) { /// only store the edges for (uint256 j = 0; j < bresTriFragments.length; j++) { fragments[nextFragmentsIx] = bresTriFragments[j]; nextFragmentsIx++; } } else { /// fill the triangle (fragments, nextFragmentsIx) = runScanline( bresTriFragments, fragments, nextFragmentsIx, canvasDim ); } } fragments = ShackledUtils.clipArray12ToLength( fragments, nextFragmentsIx ); return fragments; } /** @dev run Bresenham's line algorithm on a pair of fragments */ function runBresenhamsAlgorithm( int256[12] memory f1, int256[12] memory f2, int256 canvasDim, int256[12][] memory bresTriFragments, uint256 nextBresTriFragmentIx ) internal view returns (int256[12][] memory, uint256) { /// initiate a new set of vars BresenhamsVars memory vars; int256[12] memory fa; int256[12] memory fb; /// determine which fragment has a greater magnitude /// and set it as the destination (always order a given pair of edges the same) if ( (f1[0]**2 + f1[1]**2 + f1[2]**2) < (f2[0]**2 + f2[1]**2 + f2[2]**2) ) { fa = f1; fb = f2; } else { fa = f2; fb = f1; } vars.x = fa[0]; vars.y = fa[1]; vars.dx = ShackledMath.abs(fb[0] - fa[0]); vars.dy = -ShackledMath.abs(fb[1] - fa[1]); int256 mag = ShackledMath.hypot(vars.dx, -vars.dy); if (fa[0] < fb[0]) { vars.sx = 1; } else { vars.sx = -1; } if (fa[1] < fb[1]) { vars.sy = 1; } else { vars.sy = -1; } vars.err = vars.dx + vars.dy; vars.e2 = 0; // get the bresenhams output for this fragment pair (fa & fb) if (mag == 0) { bresTriFragments[nextBresTriFragmentIx] = fa; bresTriFragments[nextBresTriFragmentIx + 1] = fb; nextBresTriFragmentIx += 2; } else { // when mag is not 0, // the length of the result will be max of upperLimitInner // but will be clipped to remove any empty slots (bresTriFragments, nextBresTriFragmentIx) = bresenhamsInner( vars, mag, fa, fb, canvasDim, bresTriFragments, nextBresTriFragmentIx ); } return (bresTriFragments, nextBresTriFragmentIx); } /** @dev run the inner loop of Bresenham's line algorithm on a pair of fragments * (preventing stack too deep) */ function bresenhamsInner( BresenhamsVars memory vars, int256 mag, int256[12] memory fa, int256[12] memory fb, int256 canvasDim, int256[12][] memory bresTriFragments, uint256 nextBresTriFragmentIx ) internal view returns (int256[12][] memory, uint256) { // define variables to be used in the inner loop int256 ir; int256 h; /// loop through all fragments while (!(vars.x == fb[0] && vars.y == fb[1])) { /// get hypotenuse length of fragment a h = ShackledMath.hypot(fa[0] - vars.x, fa[1] - vars.y); assembly { ir := div(mul(lerpScaleFactor, h), mag) } // only add the fragment if it falls within the canvas /// create a new fragment by linear interpolation between a and b int256[12] memory newFragment = ShackledMath.vector12Lerp( fa, fb, ir, lerpScaleFactor ); newFragment[0] = vars.x; newFragment[1] = vars.y; /// save this fragment bresTriFragments[nextBresTriFragmentIx] = newFragment; ++nextBresTriFragmentIx; /// update variables to use in next iteration vars.e2 = 2 * vars.err; if (vars.e2 >= vars.dy) { vars.err += vars.dy; vars.x += vars.sx; } if (vars.e2 <= vars.dx) { vars.err += vars.dx; vars.y += vars.sy; } } /// save fragment 2 bresTriFragments[nextBresTriFragmentIx] = fb; ++nextBresTriFragmentIx; return (bresTriFragments, nextBresTriFragmentIx); } /** @dev run the scan line algorithm to fill the raster */ function runScanline( int256[12][] memory bresTriFragments, int256[12][] memory fragments, uint256 nextFragmentsIx, int256 canvasDim ) internal view returns (int256[12][] memory, uint256) { /// make a 2d array with length = num of output rows ( int256[][] memory rowFragIndices, uint256[] memory nextIxFragRows ) = getRowFragIndices(bresTriFragments, canvasDim); /// initialise a struct to hold the scanline vars ScanlineVars memory slVars; // Now iterate through the list of fragments that live in a single row for (uint256 i = 0; i < rowFragIndices.length; i++) { /// Get the left most fragment slVars.left = 4096; /// Get the right most fragment slVars.right = -4096; /// loop through the fragments in this row /// and check that a fragment was written to this row for (uint256 j = 0; j < nextIxFragRows[i]; j++) { /// What's the current fragment that we're looking at int256 fragX = bresTriFragments[uint256(rowFragIndices[i][j])][ 0 ]; // if it's lefter than our current most left frag then its the new left frag if (fragX < slVars.left) { slVars.left = fragX; slVars.leftFrag = bresTriFragments[ uint256(rowFragIndices[i][j]) ]; } // if it's righter than our current most right frag then its the new right frag if (fragX > slVars.right) { slVars.right = fragX; slVars.rightFrag = bresTriFragments[ uint256(rowFragIndices[i][j]) ]; } } /// now we need to scan from the left to the right fragment /// and interpolate as we go slVars.dx = slVars.right - slVars.left + 1; /// get the row that we're on slVars.newFragRow = slVars.leftFrag[1]; /// check that the new frag's row will be in the canvas bounds if (slVars.newFragRow >= 0 && slVars.newFragRow < canvasDim) { if (slVars.dx > int256(0)) { for (int256 j = 0; j < slVars.dx; j++) { /// calculate the column of the new fragment (its position in the scan) slVars.newFragCol = slVars.leftFrag[0] + j; /// check that the new frag's column will be in the canvas bounds if ( slVars.newFragCol >= 0 && slVars.newFragCol < canvasDim ) { slVars.ir = (j * lerpScaleFactor) / slVars.dx; /// make a new fragment by linear interpolation between left and right frags fragments[nextFragmentsIx] = ShackledMath .vector12Lerp( slVars.leftFrag, slVars.rightFrag, slVars.ir, lerpScaleFactor ); /// update its position fragments[nextFragmentsIx][0] = slVars.newFragCol; fragments[nextFragmentsIx][1] = slVars.newFragRow; nextFragmentsIx++; } } } } } return (fragments, nextFragmentsIx); } /** @dev get the row indices of each fragment in preparation for the scanline alg */ function getRowFragIndices( int256[12][] memory bresTriFragments, int256 canvasDim ) internal view returns (int256[][] memory, uint256[] memory nextIxFragRows) { uint256 canvasDimUnsigned = uint256(canvasDim); // define the length of each outer array so we can push items into it using nextIxFragRows int256[][] memory rowFragIndices = new int256[][](canvasDimUnsigned); // the inner rows can't be longer than bresTriFragments for (uint256 i = 0; i < canvasDimUnsigned; i++) { rowFragIndices[i] = new int256[](bresTriFragments.length); } // make an array the tracks for each row how many items have been pushed into it uint256[] memory nextIxFragRows = new uint256[](canvasDimUnsigned); for (uint256 f = 0; f < bresTriFragments.length; f++) { // get the row index uint256 rowIx = uint256(bresTriFragments[f][1]); // canvas_y if (rowIx >= 0 && rowIx < canvasDimUnsigned) { // get the ix of the next item to be added to the row rowFragIndices[rowIx][nextIxFragRows[rowIx]] = int256(f); ++nextIxFragRows[rowIx]; } } return (rowFragIndices, nextIxFragRows); } /** @dev run depth-testing on all fragments */ function depthTesting(int256[12][] memory fragments, int256 canvasDim) external view returns (int256[12][] memory) { uint256 canvasDimUnsigned = uint256(canvasDim); /// create a 2d array to hold the zValues of the fragments int256[][] memory zValues = ShackledMath.get2dArray( canvasDimUnsigned, canvasDimUnsigned, 0 ); /// create a 2d array to hold the fragIndex of the fragments /// as their depth is compared int256[][] memory fragIndex = ShackledMath.get2dArray( canvasDimUnsigned, canvasDimUnsigned, -1 /// -1 so we can check if a fragment was written to this location ); int256[12][] memory culledFrags = new int256[12][](fragments.length); uint256 nextFragIx = 0; /// iterate through all fragments /// and store the index of the fragment with the largest z value /// at each x, y coordinate for (uint256 i = 0; i < fragments.length; i++) { int256[12] memory frag = fragments[i]; /// x and y must be uint for indexing uint256 fragX = uint256(frag[0]); uint256 fragY = uint256(frag[1]); // console.log("checking frag", i, "z:"); // console.logInt(frag[2]); if ( (fragX < canvasDimUnsigned) && (fragY < canvasDimUnsigned) && fragX >= 0 && fragY >= 0 ) { // if this is the first fragment seen at (fragX, fragY), ie if fragIndex == 0, add it // or if this frag is closer (lower z value) than the current frag at (fragX, fragY), add it if ( fragIndex[fragX][fragY] == -1 || frag[2] >= zValues[fragX][fragY] ) { zValues[fragX][fragY] = frag[2]; fragIndex[fragX][fragY] = int256(i); } } } /// save only the fragments with prefered z values for (uint256 x = 0; x < canvasDimUnsigned; x++) { for (uint256 y = 0; y < canvasDimUnsigned; y++) { int256 fragIx = fragIndex[x][y]; /// ensure we have a valid index if (fragIndex[x][y] != -1) { culledFrags[nextFragIx] = fragments[uint256(fragIx)]; nextFragIx++; } } } return ShackledUtils.clipArray12ToLength(culledFrags, nextFragIx); } /** @dev apply lighting to the scene and update fragments accordingly */ function lightScene( int256[12][] memory fragments, ShackledStructs.LightingParams memory lp ) external view returns (int256[12][] memory) { /// create a struct for the variables to prevent stack too deep LightingVars memory lv; // calculate a constant lighting vector and its magniture lv.L = lp.lightPos; lv.lMag = ShackledMath.vector3Len(lv.L); for (uint256 f = 0; f < fragments.length; f++) { /// get the fragment's color, norm and position lv.fragCol = [fragments[f][3], fragments[f][4], fragments[f][5]]; lv.fragNorm = [fragments[f][6], fragments[f][7], fragments[f][8]]; lv.fragPos = [fragments[f][9], fragments[f][10], fragments[f][11]]; /// calculate the direction to camera / viewer and its magnitude lv.V = ShackledMath.vector3MulScalar(lv.fragPos, -1); lv.vMag = ShackledMath.vector3Len(lv.V); /// calculate the direction of the fragment normaland its magnitude lv.N = lv.fragNorm; lv.nMag = ShackledMath.vector3Len(lv.N); /// calculate the light vector per-fragment // lv.L = ShackledMath.vector3Sub(lp.lightPos, lv.fragPos); // lv.lMag = ShackledMath.vector3Len(lv.L); lv.falloff = lv.lMag**2; /// lighting intensity fall over the scene lv.lnDot = ShackledMath.vector3Dot(lv.L, lv.N); /// implement double-side rendering to account for flipped normals lv.lambertian = ShackledMath.abs(lv.lnDot); int256 specular; if (lv.lambertian > 0) { int256[3] memory normedL = ShackledMath.vector3NormX( lv.L, fidelity ); int256[3] memory normedV = ShackledMath.vector3NormX( lv.V, fidelity ); int256[3] memory H = ShackledMath.vector3Add(normedL, normedV); int256 hnDot = int256( ShackledMath.vector3Dot( ShackledMath.vector3NormX(H, fidelity), ShackledMath.vector3NormX(lv.N, fidelity) ) ); specular = calculateSpecular( lp.lightSpecPower, hnDot, fidelity, lp.inverseShininess ); } // Calculate the colour and write it into the fragment int256[3] memory colAmbi = ShackledMath.vector3Add( lv.fragCol, ShackledMath.vector3MulScalar( lp.lightColAmbi, lp.lightAmbiPower ) ); /// finalise and color the diffuse lighting int256[3] memory colDiff = ShackledMath.vector3MulScalar( lp.lightColDiff, ((lp.lightDiffPower * lv.lambertian) / (lv.lMag * lv.nMag)) / lv.falloff ); /// finalise and color the specular lighting int256[3] memory colSpec = ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar(lp.lightColSpec, specular), lv.falloff ); // add up the colour components int256[3] memory col = ShackledMath.vector3Add( ShackledMath.vector3Add(colAmbi, colDiff), colSpec ); /// update the fragment's colour in place fragments[f][3] = col[0]; fragments[f][4] = col[1]; fragments[f][5] = col[2]; } return fragments; } /** @dev calculate the specular lighting parameter */ function calculateSpecular( int256 lightSpecPower, int256 hnDot, int256 fidelity, uint256 inverseShininess ) internal pure returns (int256 specular) { int256 specAngle = hnDot > int256(0) ? hnDot : int256(0); assembly { specular := sdiv( mul(lightSpecPower, exp(specAngle, inverseShininess)), exp(fidelity, mul(inverseShininess, 2)) ) } } /** @dev get background gradient that fills the canvas */ function getBackground( int256 canvasDim, int256[3][2] memory backgroundColor ) external view returns (int256[5][] memory) { int256[5][] memory background = new int256[5][](uint256(canvasDim**2)); int256 w = canvasDim; uint256 nextIx = 0; for (int256 i = 0; i < canvasDim; i++) { for (int256 j = 0; j < canvasDim; j++) { // / write coordinates of background pixel background[nextIx][0] = j; /// x background[nextIx][1] = i; /// y // / write colours of background pixel // / get weighted average of top and bottom color according to row (i) background[nextIx][2] = /// r ((backgroundColor[0][0] * i) + (backgroundColor[1][0] * (w - i))) / w; background[nextIx][3] = /// g ((backgroundColor[0][1] * i) + (backgroundColor[1][1] * (w - i))) / w; background[nextIx][4] = /// b ((backgroundColor[0][2] * i) + (backgroundColor[1][2] * (w - i))) / w; ++nextIx; } } return background; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledStructs.sol"; library ShackledUtils { string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** @dev Flatten 3d tris array into 2d verts */ function flattenTris(int256[3][3][] memory tris) internal pure returns (int256[3][] memory) { /// initialize a dynamic in-memory array int256[3][] memory flattened = new int256[3][](3 * tris.length); for (uint256 i = 0; i < tris.length; i++) { /// tris.length == N // add values to specific index, as cannot push to array in memory flattened[(i * 3) + 0] = tris[i][0]; flattened[(i * 3) + 1] = tris[i][1]; flattened[(i * 3) + 2] = tris[i][2]; } return flattened; } /** @dev Unflatten 2d verts array into 3d tries (inverse of flattenTris function) */ function unflattenVertsToTris(int256[3][] memory verts) internal pure returns (int256[3][3][] memory) { /// initialize an array with length = 1/3 length of verts int256[3][3][] memory tris = new int256[3][3][](verts.length / 3); for (uint256 i = 0; i < verts.length; i += 3) { tris[i / 3] = [verts[i], verts[i + 1], verts[i + 2]]; } return tris; } /** @dev clip an array to a certain length (to trim empty tail slots) */ function clipArray12ToLength(int256[12][] memory arr, uint256 desiredLen) internal pure returns (int256[12][] memory) { uint256 nToCull = arr.length - desiredLen; assembly { mstore(arr, sub(mload(arr), nToCull)) } return arr; } /** @dev convert an unsigned int to a string */ function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /** @dev get the hex encoding of various powers of 2 (canvas size options) */ function getHex(uint256 _i) internal pure returns (bytes memory _hex) { if (_i == 8) { return hex"08_00_00_00"; } else if (_i == 16) { return hex"10_00_00_00"; } else if (_i == 32) { return hex"20_00_00_00"; } else if (_i == 64) { return hex"40_00_00_00"; } else if (_i == 128) { return hex"80_00_00_00"; } else if (_i == 256) { return hex"00_01_00_00"; } else if (_i == 512) { return hex"00_02_00_00"; } } /** @dev create an svg container for a bitmap (for display on svg-only platforms) */ function getSVGContainer( string memory encodedBitmap, int256 canvasDim, uint256 outputHeight, uint256 outputWidth ) internal view returns (string memory) { uint256 canvasDimUnsigned = uint256(canvasDim); // construct some elements in memory prior to return string to avoid stack too deep bytes memory imgSize = abi.encodePacked( "width='", ShackledUtils.uint2str(canvasDimUnsigned), "' height='", ShackledUtils.uint2str(canvasDimUnsigned), "'" ); bytes memory canvasSize = abi.encodePacked( "width='", ShackledUtils.uint2str(outputWidth), "' height='", ShackledUtils.uint2str(outputHeight), "'" ); bytes memory scaleStartTag = abi.encodePacked( "<g transform='scale(", ShackledUtils.uint2str(outputWidth / canvasDimUnsigned), ")'>" ); return string( abi.encodePacked( "data:image/svg+xml;base64,", Base64.encode( abi.encodePacked( "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' ", "shape-rendering='crispEdges' ", canvasSize, ">", scaleStartTag, "<image ", imgSize, " style='image-rendering: pixelated; image-rendering: crisp-edges;' ", "href='", encodedBitmap, "'/></g></svg>" ) ) ) ); } /** @dev converts raw metadata into */ function getAttributes(ShackledStructs.Metadata memory metadata) internal pure returns (bytes memory) { return abi.encodePacked( "{", '"Structure": "', metadata.geomSpec, '", "Chroma": "', metadata.colorScheme, '", "Pseudosymmetry": "', metadata.pseudoSymmetry, '", "Wireframe": "', metadata.wireframe, '", "Inversion": "', metadata.inversion, '", "Prisms": "', uint2str(metadata.nPrisms), '"}' ); } /** @dev create and encode the token's metadata */ function getEncodedMetadata( string memory image, ShackledStructs.Metadata memory metadata, uint256 tokenId ) internal view returns (string memory) { /// get attributes and description here to avoid stack too deep string memory description = '"description": "Shackled is the first general-purpose 3D renderer' " running on the Ethereum blockchain." ' Each piece represents a leap forward in on-chain computer graphics, and the collection itself is an NFT first."'; return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( string( abi.encodePacked( '{"name": "Shackled Genesis #', uint2str(tokenId), '", ', description, ', "attributes":', getAttributes(metadata), ', "image":"', image, '"}' ) ) ) ) ) ); } // fragment = // [ canvas_x, canvas_y, depth, col_x, col_y, col_z, normal_x, normal_y, normal_z, world_x, world_y, world_z ], /** @dev get an encoded 2d bitmap by combining the object and background fragments */ function getEncodedBitmap( int256[12][] memory fragments, int256[5][] memory background, int256 canvasDim, bool invert ) internal view returns (string memory) { uint256 canvasDimUnsigned = uint256(canvasDim); bytes memory fileHeader = abi.encodePacked( hex"42_4d", // BM hex"36_04_00_00", // size of the bitmap file in bytes (14 (file header) + 40 (info header) + size of raw data (1024)) hex"00_00_00_00", // 2x2 bytes reserved hex"36_00_00_00" // offset of pixels in bytes ); bytes memory infoHeader = abi.encodePacked( hex"28_00_00_00", // size of the header in bytes (40) getHex(canvasDimUnsigned), // width in pixels 32 getHex(canvasDimUnsigned), // height in pixels 32 hex"01_00", // number of color plans (must be 1) hex"18_00", // number of bits per pixel (24) hex"00_00_00_00", // type of compression (none) hex"00_04_00_00", // size of the raw bitmap data (1024) hex"C4_0E_00_00", // horizontal resolution hex"C4_0E_00_00", // vertical resolution hex"00_00_00_00", // number of used colours hex"05_00_00_00" // number of important colours ); bytes memory headers = abi.encodePacked(fileHeader, infoHeader); /// create a container for the bitmap's bytes bytes memory bytesArray = new bytes(3 * canvasDimUnsigned**2); /// write the background first so it is behind the fragments bytesArray = writeBackgroundToBytesArray( background, bytesArray, canvasDimUnsigned, invert ); bytesArray = writeFragmentsToBytesArray( fragments, bytesArray, canvasDimUnsigned, invert ); return string( abi.encodePacked( "data:image/bmp;base64,", Base64.encode(BytesUtils.MergeBytes(headers, bytesArray)) ) ); } /** @dev write the fragments to the bytes array */ function writeFragmentsToBytesArray( int256[12][] memory fragments, bytes memory bytesArray, uint256 canvasDimUnsigned, bool invert ) internal pure returns (bytes memory) { /// loop through each fragment /// and write it's color into bytesArray in its canvas equivelant position for (uint256 i = 0; i < fragments.length; i++) { /// check if x and y are both greater than 0 if ( uint256(fragments[i][0]) >= 0 && uint256(fragments[i][1]) >= 0 ) { /// calculating the starting bytesArray ix for this fragment's colors uint256 flatIx = ((canvasDimUnsigned - uint256(fragments[i][1]) - 1) * canvasDimUnsigned + (canvasDimUnsigned - uint256(fragments[i][0]) - 1)) * 3; /// red uint256 r = fragments[i][3] > 255 ? 255 : uint256(fragments[i][3]); /// green uint256 g = fragments[i][4] > 255 ? 255 : uint256(fragments[i][4]); /// blue uint256 b = fragments[i][5] > 255 ? 255 : uint256(fragments[i][5]); if (invert) { r = 255 - r; g = 255 - g; b = 255 - b; } bytesArray[flatIx + 0] = bytes1(uint8(b)); bytesArray[flatIx + 1] = bytes1(uint8(g)); bytesArray[flatIx + 2] = bytes1(uint8(r)); } } return bytesArray; } /** @dev write the fragments to the bytes array using a separate function from above to account for variable input size */ function writeBackgroundToBytesArray( int256[5][] memory background, bytes memory bytesArray, uint256 canvasDimUnsigned, bool invert ) internal pure returns (bytes memory) { /// loop through each fragment /// and write it's color into bytesArray in its canvas equivelant position for (uint256 i = 0; i < background.length; i++) { /// check if x and y are both greater than 0 if ( uint256(background[i][0]) >= 0 && uint256(background[i][1]) >= 0 ) { /// calculating the starting bytesArray ix for this fragment's colors uint256 flatIx = (uint256(background[i][1]) * canvasDimUnsigned + uint256(background[i][0])) * 3; // red uint256 r = background[i][2] > 255 ? 255 : uint256(background[i][2]); /// green uint256 g = background[i][3] > 255 ? 255 : uint256(background[i][3]); // blue uint256 b = background[i][4] > 255 ? 255 : uint256(background[i][4]); if (invert) { r = 255 - r; g = 255 - g; b = 255 - b; } bytesArray[flatIx + 0] = bytes1(uint8(b)); bytesArray[flatIx + 1] = bytes1(uint8(g)); bytesArray[flatIx + 2] = bytes1(uint8(r)); } } return bytesArray; } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[emailย protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal view returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } library BytesUtils { function char(bytes1 b) internal view returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function bytes32string(bytes32 b32) internal view returns (string memory out) { bytes memory s = new bytes(64); for (uint32 i = 0; i < 32; i++) { bytes1 b = bytes1(b32[i]); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[i * 2] = char(hi); s[i * 2 + 1] = char(lo); } out = string(s); } function hach(string memory value) internal view returns (string memory) { return bytes32string(sha256(abi.encodePacked(value))); } function MergeBytes(bytes memory a, bytes memory b) internal pure returns (bytes memory c) { // Store the length of the first array uint256 alen = a.length; // Store the length of BOTH arrays uint256 totallen = alen + b.length; // Count the loops required for array a (sets of 32 bytes) uint256 loopsa = (a.length + 31) / 32; // Count the loops required for array b (sets of 32 bytes) uint256 loopsb = (b.length + 31) / 32; assembly { let m := mload(0x40) // Load the length of both arrays to the head of the new bytes array mstore(m, totallen) // Add the contents of a to the array for { let i := 0 } lt(i, loopsa) { i := add(1, i) } { mstore( add(m, mul(32, add(1, i))), mload(add(a, mul(32, add(1, i)))) ) } // Add the contents of b to the array for { let i := 0 } lt(i, loopsb) { i := add(1, i) } { mstore( add(m, add(mul(32, add(1, i)), alen)), mload(add(b, mul(32, add(1, i)))) ) } mstore(0x40, add(m, add(32, totallen))) c := m } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library ShackledMath { /** @dev Get the minimum of two numbers */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** @dev Get the maximum of two numbers */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** @dev perform a modulo operation, with support for negative numbers */ function mod(int256 n, int256 m) internal pure returns (int256) { if (n < 0) { return ((n % m) + m) % m; } else { return n % m; } } /** @dev 'randomly' select n numbers between 0 and m (useful for getting a randomly sampled index) */ function randomIdx( bytes32 seedModifier, uint256 n, // number of elements to select uint256 m // max value of elements ) internal pure returns (uint256[] memory) { uint256[] memory result = new uint256[](n); for (uint256 i = 0; i < n; i++) { result[i] = uint256(keccak256(abi.encodePacked(seedModifier, i))) % m; } return result; } /** @dev create a 2d array and fill with a single value */ function get2dArray( uint256 m, uint256 q, int256 value ) internal pure returns (int256[][] memory) { /// Create a matrix of values with dimensions (m, q) int256[][] memory rows = new int256[][](m); for (uint256 i = 0; i < m; i++) { int256[] memory row = new int256[](q); for (uint256 j = 0; j < q; j++) { row[j] = value; } rows[i] = row; } return rows; } /** @dev get the absolute of a number */ function abs(int256 x) internal pure returns (int256) { assembly { if slt(x, 0) { x := sub(0, x) } } return x; } /** @dev get the square root of a number */ function sqrt(int256 y) internal pure returns (int256 z) { assembly { if sgt(y, 3) { z := y let x := add(div(y, 2), 1) for { } slt(x, z) { } { z := x x := div(add(div(y, x), x), 2) } } if and(slt(y, 4), sgt(y, 0)) { z := 1 } } } /** @dev get the hypotenuse of a triangle given the length of 2 sides */ function hypot(int256 x, int256 y) internal pure returns (int256) { int256 sumsq; assembly { let xsq := mul(x, x) let ysq := mul(y, y) sumsq := add(xsq, ysq) } return sqrt(sumsq); } /** @dev addition between two vectors (size 3) */ function vector3Add(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, add(mload(v1), mload(v2))) mstore( add(result, 0x20), add(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), add(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev subtraction between two vectors (size 3) */ function vector3Sub(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, sub(mload(v1), mload(v2))) mstore( add(result, 0x20), sub(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), sub(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev multiply a vector (size 3) by a constant */ function vector3MulScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, mul(mload(v), a)) mstore(add(result, 0x20), mul(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), mul(mload(add(v, 0x40)), a)) } } /** @dev divide a vector (size 3) by a constant */ function vector3DivScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, sdiv(mload(v), a)) mstore(add(result, 0x20), sdiv(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), sdiv(mload(add(v, 0x40)), a)) } } /** @dev get the length of a vector (size 3) */ function vector3Len(int256[3] memory v) internal pure returns (int256) { int256 res; assembly { let x := mload(v) let y := mload(add(v, 0x20)) let z := mload(add(v, 0x40)) res := add(add(mul(x, x), mul(y, y)), mul(z, z)) } return sqrt(res); } /** @dev scale and then normalise a vector (size 3) */ function vector3NormX(int256[3] memory v, int256 fidelity) internal pure returns (int256[3] memory result) { int256 l = vector3Len(v); assembly { mstore(result, sdiv(mul(fidelity, mload(add(v, 0x40))), l)) mstore( add(result, 0x20), sdiv(mul(fidelity, mload(add(v, 0x20))), l) ) mstore(add(result, 0x40), sdiv(mul(fidelity, mload(v)), l)) } } /** @dev get the dot-product of two vectors (size 3) */ function vector3Dot(int256[3] memory v1, int256[3] memory v2) internal view returns (int256 result) { assembly { result := add( add( mul(mload(v1), mload(v2)), mul(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ), mul(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev get the cross product of two vectors (size 3) */ function crossProduct(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore( result, sub( mul(mload(add(v1, 0x20)), mload(add(v2, 0x40))), mul(mload(add(v1, 0x40)), mload(add(v2, 0x20))) ) ) mstore( add(result, 0x20), sub( mul(mload(add(v1, 0x40)), mload(v2)), mul(mload(v1), mload(add(v2, 0x40))) ) ) mstore( add(result, 0x40), sub( mul(mload(v1), mload(add(v2, 0x20))), mul(mload(add(v1, 0x20)), mload(v2)) ) ) } } /** @dev linearly interpolate between two vectors (size 12) */ function vector12Lerp( int256[12] memory v1, int256[12] memory v2, int256 ir, int256 scaleFactor ) internal view returns (int256[12] memory result) { int256[12] memory vd = vector12Sub(v2, v1); // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), add( // v1[i] + (ir * vd[i]) / 1e3 mload(add(v1, ix)), sdiv(mul(ir, mload(add(vd, ix))), 1000) ) ) } } } /** @dev subtraction between two vectors (size 12) */ function vector12Sub(int256[12] memory v1, int256[12] memory v2) internal view returns (int256[12] memory result) { // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), sub( // v1[ix] - v2[ix] mload(add(v1, ix)), mload(add(v2, ix)) ) ) } } } /** @dev map a number from one range into another */ function mapRangeToRange( int256 num, int256 inMin, int256 inMax, int256 outMin, int256 outMax ) internal pure returns (int256 res) { assembly { res := add( sdiv( mul(sub(outMax, outMin), sub(num, inMin)), sub(inMax, inMin) ), outMin ) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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); /** * @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.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledCoords.sol"; contract XShackledCoords { constructor() {} function xconvertToWorldSpaceWithModelTransform(int256[3][3][] calldata tris,int256 scale,int256[3] calldata position) external view returns (int256[3][] memory) { return ShackledCoords.convertToWorldSpaceWithModelTransform(tris,scale,position); } function xbackfaceCulling(int256[3][3][] calldata trisWorldSpace,int256[3][3][] calldata trisCols) external view returns (int256[3][3][] memory, int256[3][3][] memory) { return ShackledCoords.backfaceCulling(trisWorldSpace,trisCols); } function xconvertToCameraSpaceViaVertexShader(int256[3][] calldata vertsWorldSpace,int256 canvasDim,bool perspCamera) external view returns (int256[3][] memory) { return ShackledCoords.convertToCameraSpaceViaVertexShader(vertsWorldSpace,canvasDim,perspCamera); } function xgetCameraMatrixOrth(int256 canvasDim) external pure returns (int256[4][4][2] memory) { return ShackledCoords.getCameraMatrixOrth(canvasDim); } function xgetCameraMatrixPersp() external pure returns (int256[4][4][2] memory) { return ShackledCoords.getCameraMatrixPersp(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledIcons.sol"; contract XShackledIcons is ShackledIcons { constructor() {} function x_getLightingParamsHash(ShackledStructs.LightingParams calldata lightingParams) external pure returns (bytes32) { return super._getLightingParamsHash(lightingParams); } function x_baseURI() external view returns (string memory) { return super._baseURI(); } function x_transferOwnership(address newOwner) external { return super._transferOwnership(newOwner); } function x_beforeTokenTransfer(address from,address to,uint256 tokenId) external { return super._beforeTokenTransfer(from,to,tokenId); } function x_safeTransfer(address from,address to,uint256 tokenId,bytes calldata _data) external { return super._safeTransfer(from,to,tokenId,_data); } function x_exists(uint256 tokenId) external view returns (bool) { return super._exists(tokenId); } function x_isApprovedOrOwner(address spender,uint256 tokenId) external view returns (bool) { return super._isApprovedOrOwner(spender,tokenId); } function x_safeMint(address to,uint256 tokenId) external { return super._safeMint(to,tokenId); } function x_safeMint(address to,uint256 tokenId,bytes calldata _data) external { return super._safeMint(to,tokenId,_data); } function x_mint(address to,uint256 tokenId) external { return super._mint(to,tokenId); } function x_burn(uint256 tokenId) external { return super._burn(tokenId); } function x_transfer(address from,address to,uint256 tokenId) external { return super._transfer(from,to,tokenId); } function x_approve(address to,uint256 tokenId) external { return super._approve(to,tokenId); } function x_setApprovalForAll(address owner,address operator,bool approved) external { return super._setApprovalForAll(owner,operator,approved); } function x_afterTokenTransfer(address from,address to,uint256 tokenId) external { return super._afterTokenTransfer(from,to,tokenId); } function x_msgSender() external view returns (address) { return super._msgSender(); } function x_msgData() external view returns (bytes memory) { return super._msgData(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledMath.sol"; contract XShackledMath { constructor() {} function xmin(int256 a,int256 b) external pure returns (int256) { return ShackledMath.min(a,b); } function xmax(int256 a,int256 b) external pure returns (int256) { return ShackledMath.max(a,b); } function xmod(int256 n,int256 m) external pure returns (int256) { return ShackledMath.mod(n,m); } function xrandomIdx(bytes32 seedModifier,uint256 n,uint256 m) external pure returns (uint256[] memory) { return ShackledMath.randomIdx(seedModifier,n,m); } function xget2dArray(uint256 m,uint256 q,int256 value) external pure returns (int256[][] memory) { return ShackledMath.get2dArray(m,q,value); } function xabs(int256 x) external pure returns (int256) { return ShackledMath.abs(x); } function xsqrt(int256 y) external pure returns (int256) { return ShackledMath.sqrt(y); } function xhypot(int256 x,int256 y) external pure returns (int256) { return ShackledMath.hypot(x,y); } function xvector3Add(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Add(v1,v2); } function xvector3Sub(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Sub(v1,v2); } function xvector3MulScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3MulScalar(v,a); } function xvector3DivScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3DivScalar(v,a); } function xvector3Len(int256[3] calldata v) external pure returns (int256) { return ShackledMath.vector3Len(v); } function xvector3NormX(int256[3] calldata v,int256 fidelity) external pure returns (int256[3] memory) { return ShackledMath.vector3NormX(v,fidelity); } function xvector3Dot(int256[3] calldata v1,int256[3] calldata v2) external view returns (int256) { return ShackledMath.vector3Dot(v1,v2); } function xcrossProduct(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.crossProduct(v1,v2); } function xvector12Lerp(int256[12] calldata v1,int256[12] calldata v2,int256 ir,int256 scaleFactor) external view returns (int256[12] memory) { return ShackledMath.vector12Lerp(v1,v2,ir,scaleFactor); } function xvector12Sub(int256[12] calldata v1,int256[12] calldata v2) external view returns (int256[12] memory) { return ShackledMath.vector12Sub(v1,v2); } function xmapRangeToRange(int256 num,int256 inMin,int256 inMax,int256 outMin,int256 outMax) external pure returns (int256) { return ShackledMath.mapRangeToRange(num,inMin,inMax,outMin,outMax); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledRasteriser.sol"; contract XShackledRasteriser { constructor() {} function xinitialiseFragments(int256[3][3][] calldata trisCameraSpace,int256[3][3][] calldata trisWorldSpace,int256[3][3][] calldata trisCols,int256 canvasDim) external view returns (int256[12][3][] memory) { return ShackledRasteriser.initialiseFragments(trisCameraSpace,trisWorldSpace,trisCols,canvasDim); } function xrasterise(int256[12][3][] calldata trisFragments,int256 canvasDim,bool wireframe) external view returns (int256[12][] memory) { return ShackledRasteriser.rasterise(trisFragments,canvasDim,wireframe); } function xrunBresenhamsAlgorithm(int256[12] calldata f1,int256[12] calldata f2,int256 canvasDim,int256[12][] calldata bresTriFragments,uint256 nextBresTriFragmentIx) external view returns (int256[12][] memory, uint256) { return ShackledRasteriser.runBresenhamsAlgorithm(f1,f2,canvasDim,bresTriFragments,nextBresTriFragmentIx); } function xbresenhamsInner(ShackledRasteriser.BresenhamsVars calldata vars,int256 mag,int256[12] calldata fa,int256[12] calldata fb,int256 canvasDim,int256[12][] calldata bresTriFragments,uint256 nextBresTriFragmentIx) external view returns (int256[12][] memory, uint256) { return ShackledRasteriser.bresenhamsInner(vars,mag,fa,fb,canvasDim,bresTriFragments,nextBresTriFragmentIx); } function xrunScanline(int256[12][] calldata bresTriFragments,int256[12][] calldata fragments,uint256 nextFragmentsIx,int256 canvasDim) external view returns (int256[12][] memory, uint256) { return ShackledRasteriser.runScanline(bresTriFragments,fragments,nextFragmentsIx,canvasDim); } function xgetRowFragIndices(int256[12][] calldata bresTriFragments,int256 canvasDim) external view returns (int256[][] memory, uint256[] memory) { return ShackledRasteriser.getRowFragIndices(bresTriFragments,canvasDim); } function xdepthTesting(int256[12][] calldata fragments,int256 canvasDim) external view returns (int256[12][] memory) { return ShackledRasteriser.depthTesting(fragments,canvasDim); } function xlightScene(int256[12][] calldata fragments,ShackledStructs.LightingParams calldata lp) external view returns (int256[12][] memory) { return ShackledRasteriser.lightScene(fragments,lp); } function xcalculateSpecular(int256 lightSpecPower,int256 hnDot,int256 fidelity,uint256 inverseShininess) external pure returns (int256) { return ShackledRasteriser.calculateSpecular(lightSpecPower,hnDot,fidelity,inverseShininess); } function xgetBackground(int256 canvasDim,int256[3][2] calldata backgroundColor) external view returns (int256[5][] memory) { return ShackledRasteriser.getBackground(canvasDim,backgroundColor); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledRenderer.sol"; contract XShackledRenderer { constructor() {} function xrender(ShackledStructs.RenderParams calldata renderParams,int256 canvasDim,bool returnSVG) external view returns (string memory) { return ShackledRenderer.render(renderParams,canvasDim,returnSVG); } function xprepareGeometryForRender(ShackledStructs.RenderParams calldata renderParams,int256 canvasDim) external view returns (int256[12][3][] memory) { return ShackledRenderer.prepareGeometryForRender(renderParams,canvasDim); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledStructs.sol"; contract XShackledStructs { constructor() {} } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledUtils.sol"; contract XShackledUtils { constructor() {} function xflattenTris(int256[3][3][] calldata tris) external pure returns (int256[3][] memory) { return ShackledUtils.flattenTris(tris); } function xunflattenVertsToTris(int256[3][] calldata verts) external pure returns (int256[3][3][] memory) { return ShackledUtils.unflattenVertsToTris(verts); } function xclipArray12ToLength(int256[12][] calldata arr,uint256 desiredLen) external pure returns (int256[12][] memory) { return ShackledUtils.clipArray12ToLength(arr,desiredLen); } function xuint2str(uint256 _i) external pure returns (string memory) { return ShackledUtils.uint2str(_i); } function xgetHex(uint256 _i) external pure returns (bytes memory) { return ShackledUtils.getHex(_i); } function xgetSVGContainer(string calldata encodedBitmap,int256 canvasDim,uint256 outputHeight,uint256 outputWidth) external view returns (string memory) { return ShackledUtils.getSVGContainer(encodedBitmap,canvasDim,outputHeight,outputWidth); } function xgetAttributes(ShackledStructs.Metadata calldata metadata) external pure returns (bytes memory) { return ShackledUtils.getAttributes(metadata); } function xgetEncodedMetadata(string calldata image,ShackledStructs.Metadata calldata metadata,uint256 tokenId) external view returns (string memory) { return ShackledUtils.getEncodedMetadata(image,metadata,tokenId); } function xgetEncodedBitmap(int256[12][] calldata fragments,int256[5][] calldata background,int256 canvasDim,bool invert) external view returns (string memory) { return ShackledUtils.getEncodedBitmap(fragments,background,canvasDim,invert); } function xwriteFragmentsToBytesArray(int256[12][] calldata fragments,bytes calldata bytesArray,uint256 canvasDimUnsigned,bool invert) external pure returns (bytes memory) { return ShackledUtils.writeFragmentsToBytesArray(fragments,bytesArray,canvasDimUnsigned,invert); } function xwriteBackgroundToBytesArray(int256[5][] calldata background,bytes calldata bytesArray,uint256 canvasDimUnsigned,bool invert) external pure returns (bytes memory) { return ShackledUtils.writeBackgroundToBytesArray(background,bytesArray,canvasDimUnsigned,invert); } } contract XBase64 { constructor() {} function xencode(bytes calldata data) external view returns (string memory) { return Base64.encode(data); } } contract XBytesUtils { constructor() {} function xchar(bytes1 b) external view returns (bytes1) { return BytesUtils.char(b); } function xbytes32string(bytes32 b32) external view returns (string memory) { return BytesUtils.bytes32string(b32); } function xhach(string calldata value) external view returns (string memory) { return BytesUtils.hach(value); } function xMergeBytes(bytes calldata a,bytes calldata b) external pure returns (bytes memory) { return BytesUtils.MergeBytes(a,b); } }
map a number from one range into another/
function mapRangeToRange( int256 num, int256 inMin, int256 inMax, int256 outMin, int256 outMax ) internal pure returns (int256 res) { assembly { res := add( sdiv( mul(sub(outMax, outMin), sub(num, inMin)), sub(inMax, inMin) ), outMin ) } }
278,844
./full_match/80001/0xEe448D42C6870009eA2F334f2F427cEe178D027A/sources/contracts/access-condition/ERC721/VWBL.sol
Get minter of NFT by tokenId tokenId The Identifier of NFT/
function getMinter(uint256 tokenId) public view returns (address) { return tokenIdToTokenInfo[tokenId].minterAddress; }
869,795
// SPDX-License-Identifier: MIT // // / / // ) ) // //____ ___ ___ //___/ / // ___ ___ / ___ // / ____ // ) ) (( ) ) // / / / __ ( // // ) ) // ) ) //\ \ // // // / / \ \ ((___/ / // ) ) // // / / // // \ \ ////____/ / ((___( ( // ) ) / / //____/ / // ((___/ / ((____ // \ \ // Developed by Dogu Deniz UGUR (https://github.com/DoguD) pragma solidity ^0.8.0; // LIBRARIES START // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } 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); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } 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} */ 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). * * * 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); } 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); } } } } // ERC20 Interface interface IERC20 { function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); 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 ); } 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 _callOptionalReturn(IERC20 token, bytes memory data) private { 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" ); } } } // LIBRARIES END // PREVIOUS EASYBLOCK CONTRACT INTERFACE interface Easyblock { function holders(uint256 _index) external view returns (address); function shareCount(address _address) external view returns (uint256); } contract EasyBlock { using SafeERC20 for IERC20; // Shareholder Info address[] public holders; mapping(address => uint256) public shareCount; mapping(address => uint256) public referFeeEarned; mapping(address => uint32) public referSaleCount; mapping(address => bool) public isShareHolder; mapping(address => bool) public isAutoCompounding; // General Info uint256 public totalShareCount; uint256 public totalShareCountAutoCompounding; uint256 public sharesInNFTs; uint32 public holderCount; uint256 public totalInvestment; uint256 public totalRewardsDistributed; uint256 public totalReferralRewardDistributed; uint256 public totalInitialFeeCollected; // Manager Info address public manager; address[] public accessWallets; uint256 public rewardFee; // per 1000 uint256 public initialFee; // per 1000 uint256 public referFee; // per 1000 of the initial fee mapping(address => uint256) public addressDiscount; // per 1000 of the initial fee uint256 public discount; // per 1000 of the initial fee address public feeCollector; // Deposit Token address public rewardToken; // Purchase Tokens address public purchaseToken; uint256 public purchaseTokenPrice; // In decimals uint256 public newInvestments; uint256 public purchaseTokenPremium; uint256 public premiumCollected; uint256 public premiumCollectedSellShare; // StrongBlock Node Holders address[] public nodeHolders; uint8 public nodeHoldersCount; uint16 public nodeCount; // Protocol controllers bool public sharePurchaseEnabled; // Experimental sell function uint256 public sellFeeDeveloper; // per 1000 uint256 public sellFeeCommunity; // per 1000 address public sellToken; uint256 public totalSharesSold; bool public isSellAllowed; uint256 public totalAmountOfSellBack; // Transfer share feature bool public isTransferEnabled; // Migration bool public isMigrating = true; address public previousContract; Easyblock easyContract; /* ======== EVENTS ======== */ event Investment( uint256 shareAmount, uint256 investmentInUSD, address shareHolder ); event ShareSold( uint256 shareCount, uint256 amountInTotal, address shareHolder ); event ShareTransfer(address from, address to, uint256 shareCount); event ToggleAutocompound(address shareHolder, bool isAutoCompounding); constructor( uint256 _rewardFee, uint256 _initialFee, uint256 _referFee, uint256 _totalInvestment, uint256 _totalRewards, address _tokenAddress, uint256 _purchaseTokenPrice, address _previousContract ) { manager = msg.sender; feeCollector = msg.sender; rewardFee = _rewardFee; initialFee = _initialFee; referFee = _referFee; totalInvestment = _totalInvestment; totalRewardsDistributed = _totalRewards; purchaseToken = _tokenAddress; sellToken = _tokenAddress; rewardToken = _tokenAddress; purchaseTokenPrice = _purchaseTokenPrice; // Migration previousContract = _previousContract; easyContract = Easyblock(previousContract); } // Experimental sell functions function setSellToken(address _sellToken) external onlyOwner { sellToken = _sellToken; } function setSellFeeDeveloper(uint256 _fee) external onlyOwner { sellFeeDeveloper = _fee; } function setSellFeeCommunity(uint256 _fee) external onlyOwner { sellFeeCommunity = _fee; } function toggleIsSellAllowed(bool _isSellAllowed) external onlyOwner { isSellAllowed = _isSellAllowed; } function getSellPrice() public view returns (uint256) { return (purchaseTokenPrice * (1000 - (sellFeeDeveloper + sellFeeCommunity))) / 1000; } function getMaxAmountOfSharesToBeSold() public view returns (uint256) { uint256 _maxAmount = newInvestments / purchaseTokenPrice; return _maxAmount; } function sellBackShares(uint256 _shareAmount) external { require(isSellAllowed, "Sell is not allowed"); require( _shareAmount <= shareCount[msg.sender], "Not enough shares to sell" ); require( _shareAmount <= getMaxAmountOfSharesToBeSold(), "Not enough shares to sell in treasury." ); uint256 _sellAmount = _shareAmount * getSellPrice(); // STATE MANIPULATIONS PRE shareCount[msg.sender] = shareCount[msg.sender] - _shareAmount; totalSharesSold += _shareAmount; // Send developer their money IERC20(sellToken).safeTransfer( feeCollector, (_shareAmount * purchaseTokenPrice * sellFeeDeveloper) / 1000 ); // Send seller their money IERC20(sellToken).safeTransfer(msg.sender, _sellAmount); // STATE MANIPULATIONS POST totalAmountOfSellBack += _sellAmount; totalShareCount -= _shareAmount; // Increase reward pool uint256 _communityFee = (_shareAmount * purchaseTokenPrice * sellFeeCommunity) / 1000; premiumCollectedSellShare += _communityFee; // Decrease new investments newInvestments -= _shareAmount * purchaseTokenPrice; emit ShareSold(_shareAmount, _sellAmount, msg.sender); } // Controller toggles function toggleSharePurchaseEnabled(bool _enabled) external onlyOwner { sharePurchaseEnabled = _enabled; } // Deposit to Purchase Methods function editPurchaseToken(address _tokenAddress) external onlyOwner { purchaseToken = _tokenAddress; } function editPurchasePrice(uint256 _price) external onlyOwner { purchaseTokenPrice = _price; } function editTokenPremium(uint256 _tokenPremium) external onlyOwner { purchaseTokenPremium = _tokenPremium; } // Deposit to Share Rewards Methods function setDepositToken(address _tokenAddress) external onlyOwner { rewardToken = _tokenAddress; } // NodeHolders function setNodeHolder(address _address) external onlyOwner { nodeHolders.push(_address); nodeHoldersCount += 1; } function setNodeCount(uint16 _count) external onlyOwner { nodeCount = _count; } // Manager Related Methods function setManager(address _address) external onlyOwner { manager = _address; } function setFeeCollector(address _address) external onlyOwner { feeCollector = _address; } function setRewardFee(uint256 _fee) external onlyOwner { rewardFee = _fee; } function setInitalFee(uint256 _fee) external onlyOwner { initialFee = _fee; } function setReferFee(uint256 _fee) external onlyOwner { referFee = _fee; } // Withdrawals function withdrawToManager(uint256 _amount) external onlyOwner { require( _amount <= newInvestments, "Not enough new investments to withdraw." ); IERC20(purchaseToken).safeTransfer(manager, _amount); newInvestments -= _amount; } function withdrawPremiumToManager() external onlyOwner { IERC20(purchaseToken).safeTransfer(manager, premiumCollected); premiumCollected = 0; } function withdrawPremiumSellToManager() external onlyOwner { IERC20(purchaseToken).safeTransfer(manager, premiumCollectedSellShare); premiumCollectedSellShare = 0; } function emergencyWithdrawal(address _token, uint256 _amount) external onlyOwner { IERC20(_token).safeTransfer(manager, _amount); } // Reward related functions function startDistribution() external onlyOwner { sharePurchaseEnabled = false; totalShareCountAutoCompounding = totalShareCount; } function endDistribution() external onlyOwner { sharePurchaseEnabled = true; totalShareCount = totalShareCountAutoCompounding; } function distributeRewardsDirectly( uint32 _start, uint32 _end, uint256 _rewardAmount ) external onlyOwner { require(!sharePurchaseEnabled, "Distribution is not allowed"); uint256 _sharePrice = getSharePrice(); uint256 _rewardPerShare = _rewardAmount / totalShareCount; for (uint32 _i = _start; _i < _end; _i++) { // Calculate the reward address _currentHolder = holders[_i]; uint256 _shareCount = shareCount[_currentHolder]; uint256 _rewardToBeDistributed = _rewardPerShare * _shareCount; // Check for auto-compounding if (isAutoCompounding[_currentHolder]) { uint256 _shareAmount = _rewardToBeDistributed / _sharePrice; shareCount[_currentHolder] = shareCount[_currentHolder] + _shareAmount; totalShareCountAutoCompounding += _shareAmount; // Updating a tmp variable so that the newly bought shares won't decrease the rewards of others } else { // Distribute IERC20(rewardToken).safeTransferFrom( msg.sender, _currentHolder, _rewardToBeDistributed ); } } } function increaseTotalRewardDistributed(uint256 _amount) external onlyOwner { totalRewardsDistributed += _amount; } function increaseTotalInvestment(uint256 _amount) external onlyOwner { totalInvestment += _amount; } // Transfer feature function toggleTransferEnabled(bool _isTransferEnabled) external onlyOwner { isTransferEnabled = _isTransferEnabled; } function transferShares(address _targetAddress, uint256 _shareAmount) external { require( msg.sender == manager || isTransferEnabled, "Can't transfer shares" ); require(shareCount[msg.sender] >= _shareAmount, "Not Enough Shares."); if (!isShareHolder[_targetAddress]) { holders.push(_targetAddress); isShareHolder[_targetAddress] = true; holderCount += 1; } shareCount[msg.sender] = shareCount[msg.sender] - _shareAmount; shareCount[_targetAddress] = shareCount[_targetAddress] + _shareAmount; emit ShareTransfer(msg.sender, _targetAddress, _shareAmount); } function getSharePrice() public view returns (uint256) { return purchaseTokenPrice + purchaseTokenPremium; } function buyShares(uint256 _shareCount, address _referer) external { require( sharePurchaseEnabled, "Shares are not purchasable at the moment." ); uint256 _totalPrice = getSharePrice(); uint256 _totalAmount = _totalPrice * _shareCount; // Initial fee uint256 _initialFeeAmount = (purchaseTokenPrice * _shareCount * initialFee) / 1000; uint256 _transferToProtocolAmount = _totalAmount - _initialFeeAmount; // Calculate address discount uint256 _addressDiscountAmount = 0; if (addressDiscount[msg.sender] != 0) { _addressDiscountAmount = (_initialFeeAmount * addressDiscount[msg.sender]) / 1000; // Reset address discount addressDiscount[msg.sender] = 0; } uint256 _discountAmount = (_initialFeeAmount * discount) / 1000; // Check for referral if ( _referer != address(0) && // Check if referer exsists _referer != msg.sender && // Check if referer is not the same as the sender isShareHolder[_referer] // Check if referer is an existing share holder ) { // Referer should be a shareholder uint256 _referFeeAmount = (_initialFeeAmount * referFee) / 1000; _initialFeeAmount -= _referFeeAmount; // Transfer the referer fee IERC20(purchaseToken).safeTransferFrom( msg.sender, _referer, _referFeeAmount ); // Increase the amount for stat reasons totalReferralRewardDistributed += _referFeeAmount; referFeeEarned[_referer] = referFeeEarned[_referer] + _referFeeAmount; referSaleCount[_referer] = referSaleCount[_referer] + 1; } // Deduce address discount _initialFeeAmount -= (_addressDiscountAmount + _discountAmount); // Transfer to protocol IERC20(purchaseToken).safeTransferFrom( msg.sender, address(this), _transferToProtocolAmount ); // Transfer of fee IERC20(purchaseToken).safeTransferFrom( msg.sender, feeCollector, _initialFeeAmount ); // Update general stats totalInitialFeeCollected += _initialFeeAmount; totalInvestment += _transferToProtocolAmount; totalShareCount += _shareCount; newInvestments += _transferToProtocolAmount - (purchaseTokenPremium * _shareCount); premiumCollected += purchaseTokenPremium * _shareCount; // Add buyer to shareholders if not included if (!isShareHolder[msg.sender]) { holders.push(msg.sender); isShareHolder[msg.sender] = true; holderCount += 1; } // Update user stats shareCount[msg.sender] = shareCount[msg.sender] + _shareCount; emit Investment( _shareCount, purchaseTokenPrice * _shareCount, msg.sender ); } // Auto-compouding function setAutoCompounding(bool _isAutoCompounding) external { isAutoCompounding[msg.sender] = _isAutoCompounding; emit ToggleAutocompound(msg.sender, _isAutoCompounding); } function getAutocompounderCount() public view returns (uint256) { uint256 _count = 0; for (uint256 _i = 0; _i < holders.length; _i++) { if (isAutoCompounding[holders[_i]]) { _count += 1; } } return _count; } // Address Discount function setAddressDiscount(address _targetAddress, uint256 _amount) external onlyOwner { addressDiscount[_targetAddress] = _amount; } // Set Discount function setDiscount(uint256 _amount) external onlyOwner { discount = _amount; } // MIGRATION START function endMigartion() external onlyOwner { isMigrating = false; } function addHolder(address _holder, uint256 _shareCount) internal { holders.push(_holder); isShareHolder[_holder] = true; shareCount[_holder] = _shareCount; holderCount += 1; } function copyFromPrevious( uint16 _start, uint16 _end, uint256 _decimals ) external onlyOwner { require(isMigrating, "Migration is not in progress."); uint256 _additionToTotalShareCount = 0; for (uint16 _i = _start; _i < _end; _i++) { // Calculate share count address _currentHolder = easyContract.holders(_i); uint256 _shareCount = easyContract.shareCount(_currentHolder) * _decimals; addHolder(_currentHolder, _shareCount); _additionToTotalShareCount += _shareCount; } totalShareCount += _additionToTotalShareCount; } // MIGRATION END // NFT RELATED START function decreaseShareCount(address _target, uint256 _amount) external hasAccess { require(isShareHolder[_target], "Target is not a shareholder."); require(shareCount[_target] >= _amount, "Not enough shares."); shareCount[_target] = shareCount[_target] - _amount; sharesInNFTs += _amount; } // NFT RELATED END // Modifiers modifier onlyOwner() { require(msg.sender == manager); _; } // Access to share count modifier function addAccess(address _address) external onlyOwner { accessWallets.push(_address); } function removeAccess(address _address) external onlyOwner { for (uint256 i; i < accessWallets.length; i++) { if (_address == accessWallets[i]) { delete accessWallets[i]; break; } } } modifier hasAccess() { bool _hasAccess = false; for (uint256 i; i < accessWallets.length; i++) { if (msg.sender == accessWallets[i]) { _hasAccess = true; break; } } require(_hasAccess); _; } }
STATE MANIPULATIONS PRE Send developer their money Send seller their money STATE MANIPULATIONS POST Increase reward pool Decrease new investments
function sellBackShares(uint256 _shareAmount) external { require(isSellAllowed, "Sell is not allowed"); require( _shareAmount <= shareCount[msg.sender], "Not enough shares to sell" ); require( _shareAmount <= getMaxAmountOfSharesToBeSold(), "Not enough shares to sell in treasury." ); uint256 _sellAmount = _shareAmount * getSellPrice(); shareCount[msg.sender] = shareCount[msg.sender] - _shareAmount; totalSharesSold += _shareAmount; IERC20(sellToken).safeTransfer( feeCollector, (_shareAmount * purchaseTokenPrice * sellFeeDeveloper) / 1000 ); IERC20(sellToken).safeTransfer(msg.sender, _sellAmount); totalAmountOfSellBack += _sellAmount; totalShareCount -= _shareAmount; uint256 _communityFee = (_shareAmount * purchaseTokenPrice * sellFeeCommunity) / 1000; premiumCollectedSellShare += _communityFee; newInvestments -= _shareAmount * purchaseTokenPrice; emit ShareSold(_shareAmount, _sellAmount, msg.sender); }
12,762,908
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; 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/ISaver.sol"; import "./interfaces/IRebalancer.sol"; import "./adaptors/AlpacaAdaptor.sol"; import "./adaptors/VenusAdaptor.sol"; // This contract is owned by Timelock. contract Saver is ISaver, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 constant SHARE_BASE = 1e18; uint256 constant RATE_BASE = 1e8; address[] public allAdaptors; // token => rebalncer mapping(address => address) public getTokenRebalancer; // token => allocations mapping(address => uint256[]) public getLastAllocations; event Rebalance(address who, address token_, address adaptor, uint256 amount); event Withdraw(address to, address token_, uint256 amount, uint256 balance); event Deposit(address who, address token_, uint256 amount, uint256 balance, address adaptor); event DoRebalance(bool lowLiquidity, uint256[] toMintAllocations, uint256 totalToMint); event DepositMultiple(address[] tokenAddresses, uint256[] adaptorAmounts); event RebalanceDeposit(address baseToken, address[] tokenAddresses, uint256[] amounts, uint256[] newAmounts); function setAdaptors(address[] memory allAdaptors_) external onlyOwner { allAdaptors = allAdaptors_; } function getAllAdaptors() external view returns (address[] memory) { return allAdaptors; } function setTokenRebalancer(address token_, address rebalancer) external onlyOwner { getTokenRebalancer[token_] = rebalancer; } function getCurrentAllocations(address token_) external view returns (address[] memory addresses, uint256[] memory amounts, uint256 total) { return _getCurrentAllocations(token_); } /** * * getAPRs * * @param token_ : token address * */ function getAPRs(address token_) public view returns (address[] memory addresses, uint256[] memory aprs) { address currAdaptor; addresses = new address[](allAdaptors.length); aprs = new uint256[](allAdaptors.length); for (uint8 i = 0; i < allAdaptors.length; i++) { currAdaptor = allAdaptors[i]; addresses[i] = currAdaptor; aprs[i] = IAdaptor(currAdaptor).getRate(token_); } } /** * * getAmount * * @param token_ : token address * @return : amount in saver */ function getAmount(address token_) external override view returns(uint256) { (address[] memory tokenAddresses, uint256[] memory amounts, uint256 totalInUnderlying) = _getCurrentAllocations(token_); return totalInUnderlying; } /** * * getRate * * @param token_ : token address * @return avgApr : avgApr */ function getRate(address token_) public view override returns (uint256 avgApr) { (, uint256[] memory amounts, uint256 total) = _getCurrentAllocations(token_); uint256 currApr; uint256 weight; for (uint256 i = 0; i < allAdaptors.length; i++) { if (amounts[i] == 0) { continue; } currApr = IAdaptor(allAdaptors[i]).getRate(token_); weight = amounts[i].mul(10**18).div(total); avgApr = avgApr.add(currApr.mul(weight).div(10**18)); } } /** * * rebalance * * @param token_ : token address * */ function rebalance(address token_) external override { _rebalance(token_, false); } function openRebalance(address token_, uint256[] calldata _newAllocations) external returns (bool, uint256 avgApr) { uint256 initialAPR = getRate(token_); // Validate and update rebalancer allocations address reblancerAddr = getTokenRebalancer[token_]; IRebalancer(reblancerAddr).setAllocations(_newAllocations, allAdaptors); bool hasRebalanced = _rebalance(token_, false); uint256 newAprAfterRebalance = getRate(token_); require(newAprAfterRebalance > initialAPR, "APR not improved"); return (hasRebalanced, newAprAfterRebalance); } function _getCurrentAllocations(address token_) internal view returns (address[] memory tokenAddresses, uint256[] memory amounts, uint256 total) { tokenAddresses = new address[](allAdaptors.length); amounts = new uint256[](allAdaptors.length); address currentAdaptorAddr; for (uint256 i = 0; i < allAdaptors.length; i++) { currentAdaptorAddr = allAdaptors[i]; tokenAddresses[i] = currentAdaptorAddr; IAdaptor _adaptor = IAdaptor(currentAdaptorAddr); amounts[i] = _adaptor.getAmount(token_); total = total.add(amounts[i]); } return (tokenAddresses, amounts, total); } function _mintWithAmounts(address token_, address[] memory tokenAddresses, uint256[] memory adaptorAmounts) internal { require(tokenAddresses.length == adaptorAmounts.length, "All tokens length != allocations length"); uint256 currAmount; emit DepositMultiple(tokenAddresses, adaptorAmounts); for(uint256 i = 0; i < adaptorAmounts.length; i++) { currAmount = adaptorAmounts[i]; if (currAmount == 0) { continue; } _depositAdaptorTokens(token_, tokenAddresses[i], currAmount); } } function _depositAdaptorTokens(address token_, address _adaptorAddr, uint256 _amount) internal returns (uint256 tokens) { if (_amount == 0) { return tokens; } IAdaptor _adaptor = IAdaptor(_adaptorAddr); uint256 balance = _contractBalanceOf(token_); emit Deposit(msg.sender, token_, _amount, balance, _adaptorAddr); require(balance >= _amount, "balance not enought"); IERC20(token_).safeTransfer(_adaptorAddr, _amount); tokens = _adaptor.deposit(token_); } function _redeemAllNeeded( address baseToken, address[] memory tokenAddresses, uint256[] memory amounts, uint256[] memory newAmounts ) internal returns ( uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity ) { require(amounts.length == newAmounts.length, 'Lengths not equal'); toMintAllocations = new uint256[](amounts.length); IAdaptor adaptor; uint256 currAmount; uint256 newAmount; address adaptorAdr; emit RebalanceDeposit(baseToken, tokenAddresses, amounts, newAmounts); // check the difference between amounts and newAmounts for (uint256 i = 0; i < amounts.length; i++) { adaptorAdr = tokenAddresses[i]; newAmount = newAmounts[i]; currAmount = amounts[i]; adaptor = IAdaptor(adaptorAdr); if (currAmount > newAmount) { toMintAllocations[i] = 0; uint256 toRedeem = currAmount.sub(newAmount); uint256 availableLiquidity = adaptor.availableLiquidity(baseToken); if (availableLiquidity < toRedeem) { lowLiquidity = true; toRedeem = availableLiquidity; } // redeem the difference _redeemProtocolTokens( adaptorAdr, baseToken, toRedeem ); } else { toMintAllocations[i] = newAmount.sub(currAmount); totalToMint = totalToMint.add(toMintAllocations[i]); } } } function _redeemProtocolTokens(address _adaptorAddr, address _token, uint256 _amount) internal returns (uint256 tokens) { if (_amount == 0) { return tokens; } tokens = IAdaptor(_adaptorAddr).withdraw(_token, _amount); } function _checkIsSame(uint256[] memory array1, uint256[] memory array2) internal returns (bool) { bool isSame = array1.length == array2.length; if (isSame) { for (uint256 i = 0; i < array1.length || !isSame; i++) { if (array1[i] != array2[i]) { isSame = false; break; } } } return isSame; } function _rebalance(address token_, bool _skipWholeRebalance) internal returns (bool) { // compare current allocations with Rebalancer's allocations uint256[] storage lastAllocations = getLastAllocations[token_]; bool isInitial = lastAllocations.length == 0; require(getTokenRebalancer[token_] != address(0), "rebalancer not exist"); uint256[] memory rebalancerLastAllocations = IRebalancer(getTokenRebalancer[token_]).getAllocations(); bool areAllocationsEqual = _checkIsSame(lastAllocations, rebalancerLastAllocations); uint256 balance = _contractBalanceOf(token_); if (areAllocationsEqual && balance == 0) { return false; } if (balance > 0) { // first time rebalance if (lastAllocations.length == 0 && _skipWholeRebalance) { // save getLastAllocations[token_] = rebalancerLastAllocations; } _mintWithAmounts(token_, allAdaptors, _amountsFromAllocations(rebalancerLastAllocations, balance)); } if (_skipWholeRebalance || areAllocationsEqual) { return false; } (address[] memory tokenAddresses, uint256[] memory amounts, uint256 totalInUnderlying) = _getCurrentAllocations(token_); uint256[] memory newAmounts = _amountsFromAllocations(rebalancerLastAllocations, totalInUnderlying); (uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity) = _redeemAllNeeded(token_, tokenAddresses, amounts, newAmounts); emit DoRebalance(lowLiquidity, toMintAllocations, totalToMint); _doRebalance(token_, lowLiquidity, toMintAllocations, totalToMint, rebalancerLastAllocations); return true; // hasRebalanced } function _doRebalance(address token_, bool lowLiquidity, uint256[] memory toMintAllocations, uint256 totalToMint, uint256[] memory rebalancerLastAllocations) internal { // liquidity do not update if (!lowLiquidity) { // Update lastAllocations with rebalancerLastAllocations delete getLastAllocations[token_]; getLastAllocations[token_] = rebalancerLastAllocations; } uint256 totalRedeemd = _contractBalanceOf(token_); if (totalRedeemd > 1 && totalToMint > 1) { // Do not mint directly using toMintAllocations check with totalRedeemd uint256[] memory tempAllocations = new uint256[](toMintAllocations.length); for (uint256 i = 0; i < toMintAllocations.length; i++) { // Calc what would have been the correct allocations percentage if all was available tempAllocations[i] = toMintAllocations[i].mul(100000).div(totalToMint); } uint256[] memory partialAmounts = _amountsFromAllocations(tempAllocations, totalRedeemd); _mintWithAmounts(token_, allAdaptors, partialAmounts); } } /** * Calculate amounts from percentage allocations (100000 => 100%) * * @param allocations : array of protocol allocations in percentage * @param total : total amount * @return : array with amounts */ function _amountsFromAllocations(uint256[] memory allocations, uint256 total) internal pure returns (uint256[] memory) { uint256[] memory newAmounts = new uint256[](allocations.length); uint256 currBalance = 0; uint256 allocatedBalance = 0; for (uint256 i = 0; i < allocations.length; i++) { if (i == allocations.length - 1) { newAmounts[i] = total.sub(allocatedBalance); } else { currBalance = total.mul(allocations[i]).div(100000); allocatedBalance = allocatedBalance.add(currBalance); newAmounts[i] = currBalance; } } return newAmounts; } /** * * contractBalanceOf * * @param _token : token address * @return : balance */ function _contractBalanceOf(address _token) private view returns (uint256) { // Original implementation: // // return IERC20(_token).balanceOf(address(this)); // Optimized implementation inspired by uniswap https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/UniswapV3Pool.sol#L144 // // 0x70a08231 -> selector for 'function balanceOf(address) returns (uint256)' (bool success, bytes memory data) = _token.staticcall(abi.encodeWithSelector(0x70a08231, address(this))); require(success); return abi.decode(data, (uint256)); } /** * * Withdraw from Saver * * @param token_ : token address * @param amount_ : amount * @param toAddress_ : to */ function withdraw(address token_, uint256 amount_, address toAddress_) external override { uint256 amountTo = amount_; for (uint8 i = 0; i < allAdaptors.length; i++) { address adaptorAddr = allAdaptors[i]; IAdaptor _adaptor = IAdaptor(adaptorAddr); uint256 allAmount = _adaptor.getAmount(token_); // same or greater if (allAmount >= amountTo) { _adaptor.withdraw(token_, amountTo); amountTo = amountTo.sub(allAmount); } else { _adaptor.withdraw(token_, amountTo); } } uint256 balance = IERC20(token_).balanceOf(address(this)); if (balance > 0) { IERC20(token_).safeTransfer(toAddress_, amount_); } else { if (address(this).balance > 0) { // native token? SafeToken.safeTransferETH(toAddress_, amount_); } } emit Withdraw(toAddress_, token_, amount_, balance); } fallback() external payable{} }
Validate and update rebalancer allocations
function openRebalance(address token_, uint256[] calldata _newAllocations) external returns (bool, uint256 avgApr) { uint256 initialAPR = getRate(token_); address reblancerAddr = getTokenRebalancer[token_]; IRebalancer(reblancerAddr).setAllocations(_newAllocations, allAdaptors); bool hasRebalanced = _rebalance(token_, false); uint256 newAprAfterRebalance = getRate(token_); require(newAprAfterRebalance > initialAPR, "APR not improved"); return (hasRebalanced, newAprAfterRebalance); }
1,836,724
./full_match/4/0xA513B3b0E4430Dd466860E3e7C58E5Cad22594a4/sources/_thirdweb-dev/contracts/extension/BatchMintMetadata.sol
Returns the id for the batch of tokens the given tokenId belongs to.
function getBatchIdAtIndex(uint256 _index) public view returns (uint256) { if (_index >= getBaseURICount()) { revert("Invalid index"); } return batchIds[_index]; }
809,855
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // ============ Errors ============ error InvalidAmount(); // ============ Inferfaces ============ interface IERC20Capped is IERC20 { function cap() external returns(uint256); } // ============ Contract ============ contract ERC20Backed is AccessControl, ReentrancyGuard, Pausable { using Address for address; using SafeMath for uint256; // ============ Events ============ event ERC20Received(address indexed sender, uint256 amount); event ERC20Sent(address indexed recipient, uint256 amount); event Capitalized(address from, uint256 amount); // ============ Constants ============ bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant CURATOR_ROLE = keccak256("CURATOR_ROLE"); bytes32 public constant WITHDRAWER_ROLE = keccak256("WITHDRAWER_ROLE"); //this is the contract address for the ERC20 token IERC20Capped public immutable TOKEN; //this is the token cap of the ERC20 token uint256 public immutable TOKEN_CAP; // ============ Store ============ //the eth balance allocated for withdrawal uint256 private _interestAmount; //the buy amount percent to allocate for withdrawal //where 10000 = 100.00% uint256 private _interestPercent; //the buy for amount percent //where 10000 = 100.00% uint256 private _buyForPercent; //the sell for amount percent //where 10000 = 100.00% uint256 private _sellForPercent; // ============ Deploy ============ /** * @dev Grants `DEFAULT_ADMIN_ROLE` to the account that deploys the * contract. */ constructor( IERC20Capped token, uint256 interestPercent, uint256 buyForPercent, uint256 sellForPercent, address admin ) payable { //set up roles for the admin _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(PAUSER_ROLE, admin); //set the ERC20 token addresses TOKEN = token; //set the token cap TOKEN_CAP = token.cap(); //set the percents _interestPercent = interestPercent; _buyForPercent = buyForPercent; _sellForPercent = sellForPercent; } /** * @dev The Ether received will be logged with {PaymentReceived} * events. Note that these events are not fully reliable: it's * possible for a contract to receive Ether without triggering this * function. This only affects the reliability of the events, and not * the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit Capitalized(_msgSender(), msg.value); } // ============ Read Methods ============ /** * @dev Returns the ether balance */ function balanceEther() public view returns(uint256) { return address(this).balance - _interestAmount; } /** * @dev Returns the ERC20 token balance */ function balanceToken() public view returns(uint256) { return TOKEN.balanceOf(address(this)); } /** * @dev Returns the ether amount we are willing to buy ERC20 token for */ function buyingFor(uint256 amount) public view returns(uint256) { return _buyingFor(amount, balanceEther()); } /** * @dev Returns the ether amount we are willing to sell ERC20 token for */ function sellingFor(uint256 amount) public view returns(uint256) { return _sellingFor(amount, balanceEther()); } // ============ Write Methods ============ /** * @dev Buys `amount` of ERC20 token */ function buy(address recipient, uint256 amount) public payable whenNotPaused nonReentrant { uint256 value = _sellingFor(amount, balanceEther() - msg.value); if (value == 0 || msg.value < value || balanceToken() < amount ) revert InvalidAmount(); //we already received the ether //so just send the tokens SafeERC20.safeTransfer(TOKEN, recipient, amount); //add to the interest _interestAmount += msg.value.mul(_interestPercent).div(10000); //emit the sent event emit ERC20Sent(recipient, amount); } /** * @dev Sells `amount` of ERC20 token */ function sell(address recipient, uint256 amount) public whenNotPaused nonReentrant { //check allowance if(TOKEN.allowance(recipient, address(this)) < amount) revert InvalidAmount(); //send the ether Address.sendValue(payable(recipient), buyingFor(amount)); //now accept the payment SafeERC20.safeTransferFrom(TOKEN, recipient, address(this), amount); emit ERC20Received(recipient, amount); } // ============ Admin Methods ============ /** * @dev Sets the buy for percent */ function buyFor(uint256 percent) public virtual onlyRole(CURATOR_ROLE) { _buyForPercent = percent; } /** * @dev Sets the interest */ function interest(uint256 percent) public virtual onlyRole(CURATOR_ROLE) { _interestPercent = percent; } /** * @dev Pauses all token transfers. */ function pause() public virtual onlyRole(PAUSER_ROLE) { _pause(); } /** * @dev Sets the sell for percent */ function sellFor(uint256 percent) public virtual onlyRole(CURATOR_ROLE) { _sellForPercent = percent; } /** * @dev Withdraws interest. */ function withdraw(address recipient) public virtual nonReentrant onlyRole(WITHDRAWER_ROLE) { //send the interest Address.sendValue(payable(recipient), _interestAmount); _interestAmount = 0; } /** * @dev Unpauses all token transfers. */ function unpause() public virtual onlyRole(PAUSER_ROLE) { _unpause(); } // ============ Internal Methods ============ /** * @dev Returns the ether amount we are willing to buy ERC20 token for */ function _buyingFor(uint256 amount, uint256 balance) internal view returns(uint256) { // (eth / cap) * amount return balance.mul(amount).mul(_buyForPercent).div(TOKEN_CAP).div(1000); } /** * @dev Returns the ether amount we are willing to sell ERC20 token for */ function _sellingFor(uint256 amount, uint256 balance) internal view returns(uint256) { // (eth / cap) * amount return balance.mul(amount).mul(_sellForPercent).div(TOKEN_CAP).div(1000); } }
Returns the ether balance/
function balanceEther() public view returns(uint256) { return address(this).balance - _interestAmount; }
5,480,364
./full_match/1/0x748A0F458B9E71061ca0aC543B984473F203E1CB/sources/contracts/core/LiqLocker.sol
Lookup a value in a list of (sorted) checkpoints. Copied from oz/ERC20Votes.sol/
function _checkpointsLookup(DelegateeCheckpoint[] storage ckpts, uint256 epochStart) private view returns (DelegateeCheckpoint memory) { uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = AuraMath.average(low, high); if (ckpts[mid].epochStart > epochStart) { high = mid; low = mid + 1; } } return high == 0 ? DelegateeCheckpoint(0, 0) : ckpts[high - 1]; }
9,644,503
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * 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 Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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. */ 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); _; } } /* * @title ENC ECO System, build in Heco Network * @dev A financial system built on smart contract technology. Open to all, transparent to all. * The worlds first decentralized, community support fund */ contract EncEcosystem is Ownable { IERC20 public invest1ccToken; IERC20 public investEncToken; using SafeMath for uint256; struct PlayerDeposit { uint256 id; uint256 amount; uint256 total_withdraw; uint256 time; uint256 period; uint256 month; uint256 expire; uint8 status; uint8 is_crowd; } struct Player { address referral; uint8 is_supernode; uint256 level_id; uint256 dividends; uint256 referral_bonus; uint256 match_bonus; uint256 supernode_bonus; uint256 total_invested; uint256 total_redeem; uint256 total_withdrawn; uint256 last_payout; PlayerDeposit[] deposits; address[] referrals; } struct PlayerTotal { uint256 total_match_invested; uint256 total_dividends; uint256 total_referral_bonus; uint256 total_match_bonus; uint256 total_supernode_bonus; uint256 total_period1_invested; uint256 total_period2_invested; uint256 total_period3_invested; uint256 total_period4_invested; uint256 total_period1_devidends; uint256 total_period2_devidends; uint256 total_period3_devidends; uint256 total_period4_devidends; } /* Deposit smart contract address */ address public invest_1cc_token_address = 0xFAd7161C74c809C213D88DAc021600D74F6c961c; uint256 public invest_1cc_token_decimal = 4; address public invest_enc_token_address = 0x73724d56fE952bf2eD130A6fb31C1f58dDEdac68; uint256 public invest_enc_token_decimal = 8; /* Platform bonus address */ address public platform_bonus_address = 0x6Fc447828B90d7D7f6C84d5fa688FF3E4ED3763C; /* Platform bonus rate percent(%) */ uint256 constant public platform_bonus_rate = 3; uint256 public total_investors; uint256 public total_invested; uint256 public total_withdrawn; uint256 public total_redeem; uint256 public total_dividends; uint256 public total_referral_bonus; uint256 public total_match_bonus; uint256 public total_supernode_bonus; uint256 public total_platform_bonus; /* Current joined supernode count */ uint256 public total_supernode_num; /* Total supernode join limit number */ uint256 constant public SUPERNODE_LIMIT_NUM = 100; uint256[] public supernode_period_ids = [1, 2, 3]; //period months uint256[] public supernode_period_amounts = [5000,6000,7000]; //period amount uint256[] public supernode_period_limits = [20, 30, 50]; //period limit //supernode total numer in which period uint256[] public total_supernode_num_periods = [0,0,0]; /* Super Node bonus rate */ uint256 constant public supernode_bonus_rate = 30; /* Referral bonuses data define*/ uint8[] public referral_bonuses = [6,4,2,1,1,1,1,1,1,1]; /* Invest period and profit parameter definition */ uint256 constant public invest_early_redeem_feerate = 15; //invest early redeem fee rate(%) uint256[] public invest_period_ids = [1, 2, 3, 4]; //period ids uint256[] public invest_period_months = [3, 6, 12, 24]; //period months uint256[] public invest_period_rates = [600, 700, 800, 900]; //Ten thousand of month' rate uint256[] public invest_period_totals = [0, 0, 0, 0]; //period total invested uint256[] public invest_period_devidends = [0, 0, 0, 0]; //period total devidends /* withdraw fee amount (0.8 1CC)) */ uint256 constant public withdraw_fee_amount = 8000; /* yield reduce project section config, item1: total yield, item2: reduce rate */ uint256[] public yield_reduce_section1 = [30000, 30]; uint256[] public yield_reduce_section2 = [60000, 30]; uint256[] public yield_reduce_section3 = [90000, 30]; uint256[] public yield_reduce_section4 = [290000, 30]; uint256[] public yield_reduce_section5 = [800000, 30]; /* Team level data definition */ uint256[] public team_level_ids = [1,2,3,4,5,6]; uint256[] public team_level_amounts = [1000,3000,5000,10000,20000,50000]; uint256[] public team_level_bonuses = [2,4,6,8,10,12]; /* Crowd period data definition */ uint256[] public crowd_period_ids = [1,2,3]; uint256[] public crowd_period_rates = [4,5,6]; uint256[] public crowd_period_limits = [50000,30000,20000]; /* Total (period) crowd number*/ uint256[] public total_crowd_num_periods = [0,0,0]; /* user invest min amount */ uint256 constant public INVEST_MIN_AMOUNT = 10000000; /* user invest max amount */ uint256 constant public INVEST_MAX_AMOUNT = 100000000000000; /* user crowd limit amount */ uint256 constant public SUPERNODE_LIMIT_AMOUNT = 5000; /* user crowd period(month) */ uint256 constant public crowd_period_month = 24; uint256 constant public crowd_period_start = 1634313600; /* Mapping data list define */ mapping(address => Player) public players; mapping(address => PlayerTotal) public playerTotals; mapping(uint256 => address) public addrmap; address[] public supernodes; event Deposit(address indexed addr, uint256 amount, uint256 month); event Withdraw(address indexed addr, uint256 amount); event Crowd(address indexed addr, uint256 period,uint256 amount); event SuperNode(address indexed addr, uint256 _period, uint256 amount); event DepositRedeem(uint256 invest_id); event ReferralPayout(address indexed addr, uint256 amount, uint8 level); event SetReferral(address indexed addr,address refferal); constructor() public { /* Create invest token instace */ invest1ccToken = IERC20(invest_1cc_token_address); investEncToken = IERC20(invest_enc_token_address); } /* Function to receive Ether. msg.data must be empty */ receive() external payable {} /* Fallback function is called when msg.data is not empty */ fallback() external payable {} function getBalance() public view returns (uint) { return address(this).balance; } /* * @dev user do set refferal action */ function setReferral(address _referral) payable external { Player storage player = players[msg.sender]; require(player.referral == address(0), "Referral has been set"); require(_referral != address(0), "Invalid Referral address"); Player storage ref_player = players[_referral]; require(ref_player.referral != address(0) || _referral == platform_bonus_address, "Referral address not activated yet"); _setReferral(msg.sender,_referral); emit SetReferral(msg.sender,_referral); } /* * @dev user do join shareholder action, to join SUPERNODE */ function superNode(address _referral, uint256 _period, uint256 _amount) payable external { Player storage player = players[msg.sender]; require(player.is_supernode == 0, "Already a supernode"); require(_period >= 1 && _period <= 3 , "Invalid Period Id"); if(_period > 1){ uint256 _lastPeriodLimit = supernode_period_limits[_period-2]; require(total_supernode_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet "); } uint256 _periodAmount = supernode_period_amounts[_period-1]; require(_amount == _periodAmount, "Not match the current round limit"); //valid period remain uint256 _periodRemain = supernode_period_limits[_period-1] - total_supernode_num_periods[_period-1]; require(_periodRemain > 0, "Out of current period limit"); /* format token amount */ uint256 token_amount = _getTokenAmount(_amount,invest_1cc_token_decimal); /* Transfer user address token to contract address*/ require(invest1ccToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* set the player of supernodes roles */ player.is_supernode = 1; total_supernode_num += 1; total_supernode_num_periods[_period-1] += 1; /* push user to shareholder list*/ supernodes.push(msg.sender); emit SuperNode(msg.sender, _period, _amount); } /* * @dev user do crowd action, to get enc */ function crowd(address _referral, uint256 _period, uint256 _amount) payable external { require(_period >= 1 && _period <= 3 , "Invalid Period Id"); if(_period > 1){ uint256 _lastPeriodLimit = crowd_period_limits[_period-2]; require(total_crowd_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet "); } //valid period remain uint256 _periodRemain = crowd_period_limits[_period-1] - total_crowd_num_periods[_period-1]; require(_periodRemain > 0, "Out of current period limit"); uint256 _periodRate = crowd_period_rates[_period-1]; uint256 token_enc_amount = _getTokenAmount(_amount,invest_enc_token_decimal); uint256 token_1cc_amount = _getTokenAmount(_amount.mul(_periodRate),invest_1cc_token_decimal); /* Transfer user address token to contract address*/ require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* get the period total time (total secones) */ uint256 _period_ = 4; uint256 _month = crowd_period_month; uint256 period_time = _month.mul(30).mul(86400); //updater period total number total_crowd_num_periods[_period-1] += _amount; Player storage player = players[msg.sender]; /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: token_enc_amount, total_withdraw: 0, time: uint256(block.timestamp), period: _period_, month: _month, expire: uint256(block.timestamp).add(period_time), status: 0, is_crowd: 1 })); //update total invested player.total_invested += token_enc_amount; total_invested += token_enc_amount; invest_period_totals[_period_-1] += token_enc_amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period_, token_enc_amount, 1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1); emit Crowd(msg.sender, _period, _amount); } /* * @dev user do deposit action,grant the referrs bonus,grant the shareholder bonus,grant the match bonus */ function deposit(address _referral, uint256 _amount, uint256 _period) external payable { require(_period >= 1 && _period <= 4 , "Invalid Period Id"); uint256 _month = invest_period_months[_period-1]; /* format token amount */ uint256 _decimal = invest_enc_token_decimal - invest_1cc_token_decimal; uint256 token_enc_amount = _amount; uint256 token_1cc_amount = _amount.div(10**_decimal); require(token_enc_amount >= INVEST_MIN_AMOUNT, "Minimal deposit: 0.1 enc"); require(token_enc_amount <= INVEST_MAX_AMOUNT, "Maxinum deposit: 1000000 enc"); Player storage player = players[msg.sender]; require(player.deposits.length < 2000, "Max 2000 deposits per address"); /* Transfer user address token to contract address*/ require(investEncToken.transferFrom(msg.sender, address(this), token_enc_amount), "transferFrom failed"); require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } /* get the period total time (total secones) */ uint256 period_time = _month.mul(30).mul(86400); uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: token_enc_amount, total_withdraw: 0, time: uint256(block.timestamp), period: _period, month: _month, expire:uint256(block.timestamp).add(period_time), status: 0, is_crowd: 0 })); player.total_invested += token_enc_amount; total_invested += token_enc_amount; invest_period_totals[_period-1] += token_enc_amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period, token_enc_amount, 1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1); emit Deposit(msg.sender, _amount, _month); } /* * @dev user do withdraw action, tranfer the total profit to user account, grant rereferral bonus, grant match bonus, grant shareholder bonus */ function withdraw() payable external { /* update user dividend data */ _payout(msg.sender); Player storage player = players[msg.sender]; uint256 _amount = player.dividends + player.referral_bonus + player.match_bonus + player.supernode_bonus; require(_amount >= 10000000, "Minimal payout: 0.1 ENC"); /* format deposit token amount */ uint256 token_enc_amount = _amount; /* process token transfer action */ require(investEncToken.approve(address(this), token_enc_amount), "approve failed"); require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed"); /*transfer service fee to contract*/ uint256 token_1cc_fee_amount = withdraw_fee_amount; require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_fee_amount), "transferFrom failed"); uint256 _dividends = player.dividends; /* Update user total payout data */ _updatePlayerTotalPayout(msg.sender, token_enc_amount); /* Grant referral bonus */ _referralPayout(msg.sender, _dividends); /* Grant super node bonus */ _superNodesPayout(_dividends); /* Grant team match bonus*/ _matchPayout(msg.sender, _dividends); emit Withdraw(msg.sender, token_enc_amount); } /* * @dev user do deposit redeem action,transfer the expire deposit's amount to user account */ function depositRedeem(uint256 _invest_id) payable external { Player storage player = players[msg.sender]; require(player.deposits.length >= _invest_id && _invest_id > 0, "Valid deposit id"); uint256 _index = _invest_id - 1; require(player.deposits[_index].status == 0, "Invest is redeemed"); //crowded deposit can't do early redeem action //if(player.deposits[_index].is_crowd == 1) { require(player.deposits[_index].expire < block.timestamp, "Invest not expired"); //} /* formt deposit token amount */ uint256 token_enc_amount = player.deposits[_index].amount; //deposit is not expired, deduct the fee (10%) if(player.deposits[_index].expire > block.timestamp){ //token_enc_amount = token_enc_amount * (100 - invest_early_redeem_feerate) / 100; } /* process token transfer action*/ require(investEncToken.approve(address(this), token_enc_amount), "approve failed"); require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed"); /* update deposit status in redeem */ player.deposits[_index].status = 1; uint256 _amount = player.deposits[_index].amount; /* update user token balance*/ player.total_invested -= _amount; /* update total invested/redeem amount */ total_invested -= _amount; total_redeem += _amount; /* update invest period total invested amount*/ uint256 _period = player.deposits[_index].period; invest_period_totals[_period-1] -= _amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period, _amount, -1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, -1); emit DepositRedeem(_invest_id); } /* * @dev Update Referral Match invest amount, total investor number, map investor address index */ function _updateReferralMatchInvestedAmount(address _addr,uint256 _amount,int8 _opType) private { if(_opType > 0) { playerTotals[_addr].total_match_invested += _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested += _amount; ref = players[ref].referral; } }else{ playerTotals[_addr].total_match_invested -= _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested -= _amount; ref = players[ref].referral; } } } /* * @dev Update user total payout data */ function _updatePlayerTotalPayout(address _addr,uint256 token_amount) private { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* update user Withdraw total amount*/ player.total_withdrawn += token_amount; playerTotal.total_dividends += player.dividends; playerTotal.total_referral_bonus += player.referral_bonus; playerTotal.total_match_bonus += player.match_bonus; playerTotal.total_supernode_bonus += player.supernode_bonus; /* update platform total data*/ total_withdrawn += token_amount; total_dividends += player.dividends; total_referral_bonus += player.referral_bonus; total_match_bonus += player.match_bonus; total_supernode_bonus += player.supernode_bonus; uint256 _platform_bonus = (token_amount * platform_bonus_rate / 100); total_platform_bonus += _platform_bonus; /* update platform address bonus*/ players[platform_bonus_address].match_bonus += _platform_bonus; /* reset user bonus data */ player.dividends = 0; player.referral_bonus = 0; player.match_bonus = 0; player.supernode_bonus = 0; } /* * @dev get user deposit expire status */ function _getExpireStatus(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; uint256 _status = 1; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { _status = 0; break; } } return _status; } /* * @dev update user referral data */ function _setReferral(address _addr, address _referral) private { /* if user referral is not set */ if(players[_addr].referral == address(0) && _referral != _addr && _referral != address(0)) { Player storage ref_player = players[_referral]; if(ref_player.referral != address(0) || _referral == platform_bonus_address){ players[_addr].referral = _referral; /* update user referral address list*/ players[_referral].referrals.push(_addr); } } } /* * @dev Grant user referral bonus in user withdraw */ function _referralPayout(address _addr, uint256 _amount) private { address ref = players[_addr].referral; uint256 _day_payout = _payoutOfDay(_addr); if(_day_payout == 0) return; for(uint8 i = 0; i < referral_bonuses.length; i++) { if(ref == address(0)) break; uint256 _ref_day_payout = _payoutOfDay(ref); uint256 _token_amount = _amount; /* user bonus double burn */ if(_ref_day_payout * 2 < _day_payout){ _token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout; } //validate account deposit is all expired or not uint256 _is_expire = _getExpireStatus(ref); if(_is_expire == 0) { uint256 bonus = _token_amount * referral_bonuses[i] / 100; players[ref].referral_bonus += bonus; } ref = players[ref].referral; } } /* * @dev Grant shareholder full node bonus in user withdraw */ function _superNodesPayout(uint256 _amount) private { uint256 _supernode_num = supernodes.length; if(_supernode_num == 0) return; uint256 bonus = _amount * supernode_bonus_rate / 100 / _supernode_num; for(uint256 i = 0; i < _supernode_num; i++) { address _addr = supernodes[i]; players[_addr].supernode_bonus += bonus; } } /* * @dev Grant Match bonus in user withdraw */ function _matchPayout(address _addr,uint256 _amount) private { /* update player team level */ _upgradePlayerTeamLevel(_addr); uint256 last_level_id = players[_addr].level_id; /* player is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) return; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; //validate account deposit is all expired or not uint256 _is_expire = _getExpireStatus(ref); /* upgrade player team level id*/ _upgradePlayerTeamLevel(ref); if(players[ref].level_id > last_level_id){ uint256 last_level_bonus = 0; if(last_level_id > 0){ last_level_bonus = team_level_bonuses[last_level_id-1]; } uint256 cur_level_bonus = team_level_bonuses[players[ref].level_id-1]; uint256 bonus_amount = _amount * (cur_level_bonus - last_level_bonus) / 100; if(_is_expire==0){ players[ref].match_bonus += bonus_amount; } last_level_id = players[ref].level_id; /* referral is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) break; } ref = players[ref].referral; } } /* * @dev upgrade player team level id */ function _upgradePlayerTeamLevel(address _addr) private { /* get community total invested*/ uint256 community_total_invested = _getCommunityTotalInvested(_addr); uint256 level_id = 0; for(uint8 i=0; i < team_level_ids.length; i++){ uint256 _team_level_amount = _getTokenAmount(team_level_amounts[i], invest_enc_token_decimal); if(community_total_invested >= _team_level_amount){ level_id = team_level_ids[i]; } } players[_addr].level_id = level_id; } /* * @dev Get community total invested */ function _getCommunityTotalInvested(address _addr) view private returns(uint256 value) { address[] memory referrals = players[_addr].referrals; uint256 nodes_max_invested = 0; uint256 nodes_total_invested = 0; for(uint256 i=0;i<referrals.length;i++){ address ref = referrals[i]; nodes_total_invested += playerTotals[ref].total_match_invested; if(playerTotals[ref].total_match_invested > nodes_max_invested){ nodes_max_invested = playerTotals[ref].total_match_invested; } } return (nodes_total_invested - nodes_max_invested); } /* * @dev user withdraw, user devidends data update */ function _payout(address _addr) private { uint256 payout = this.payoutOf(_addr); if(payout > 0) { _updateTotalPayout(_addr); players[_addr].last_payout = uint256(block.timestamp); players[_addr].dividends += payout; } } /* * @dev format token amount with token decimal */ function _getTokenAmount(uint256 _amount,uint256 _token_decimal) pure private returns(uint256 token_amount) { uint256 token_decimals = 10 ** _token_decimal; token_amount = _amount * token_decimals; return token_amount; } /* * @dev update user total withdraw data */ function _updateTotalPayout(address _addr) private { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); uint256 _dep_payout = _day_payout * (to - from) / 86400; uint256 _period = player.deposits[i].period; player.deposits[i].total_withdraw += _dep_payout; invest_period_devidends[_period-1]+= _dep_payout; //update player period total devidend data _updatePlayerPeriodTotalDevidendsData(msg.sender,_period,_dep_payout); } } } /* * @dev update player period total invest data */ function _updatePlayerPeriodTotalInvestedData(address _addr,uint256 _period,uint256 _token_amount,int8 _opType) private { if(_opType==-1){ if(_period==1){ playerTotals[_addr].total_period1_invested -= _token_amount; return; } if(_period==2){ playerTotals[_addr].total_period2_invested -= _token_amount; return; } if(_period==3){ playerTotals[_addr].total_period3_invested -= _token_amount; return; } if(_period==4){ playerTotals[_addr].total_period4_invested -= _token_amount; return; } }else{ if(_period==1){ playerTotals[_addr].total_period1_invested += _token_amount; return; } if(_period==2){ playerTotals[_addr].total_period2_invested += _token_amount; return; } if(_period==3){ playerTotals[_addr].total_period3_invested += _token_amount; return; } if(_period==4){ playerTotals[_addr].total_period4_invested += _token_amount; return; } } } /* * @dev update player period total devidend data */ function _updatePlayerPeriodTotalDevidendsData(address _addr,uint256 _period,uint256 _dep_payout) private { if(_period==1){ playerTotals[_addr].total_period1_devidends += _dep_payout; return; } if(_period==2){ playerTotals[_addr].total_period2_devidends += _dep_payout; return; } if(_period==3){ playerTotals[_addr].total_period3_devidends += _dep_payout; return; } if(_period==4){ playerTotals[_addr].total_period4_devidends += _dep_payout; return; } } /* * @dev get the invest period rate, if total yield reached reduce limit, invest day rate will be reduce */ function _getInvestDayPayoutOf(uint256 _amount, uint256 _period) view private returns(uint256 value) { /* get invest period base rate*/ uint256 period_month_rate = invest_period_rates[_period-1]; /* format amount with token decimal */ uint256 token_amount = _amount; value = token_amount * period_month_rate / 30 / 10000; if(value > 0){ /* total yield reached 30,000,start first reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section1[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section1[1]) / 100; } /* total yield reached 60,000,start second reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section2[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section2[1]) / 100; } /* total yield reached 90,000,start third reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section3[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section3[1]) / 100; } /* total yield reached 290,000,start fourth reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section4[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section4[1]) / 100; } /* total yield reached 890,000,start fifth reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section5[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section5[1]) / 100; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function payoutOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); value += _day_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function _payoutOfDay(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; //uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; //uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount, dep.period); value += _day_payout; } } return value; } /* * @dev Remove supernodes of the special address */ function _removeSuperNodes(address _addr) private { for (uint index = 0; index < supernodes.length; index++) { if(supernodes[index] == _addr){ for (uint i = index; i < supernodes.length-1; i++) { supernodes[i] = supernodes[i+1]; } delete supernodes[supernodes.length-1]; break; } } } /* * @dev get contract data info * @return total invested,total investor number,total withdraw,total referral bonus */ function contractInfo() view external returns( uint256 _total_invested, uint256 _total_investors, uint256 _total_withdrawn, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_platform_bonus, uint256 _total_supernode_num, uint256 _crowd_period_month, uint256 _crowd_period_start, uint256 _total_holder_bonus, uint256 _total_match_bonus) { return ( total_invested, total_investors, total_withdrawn, total_dividends, total_referral_bonus, total_platform_bonus, total_supernode_num, crowd_period_month, crowd_period_start, total_supernode_bonus, total_match_bonus ); } /* * @dev get user info * @return pending withdraw amount,referral,rreferral num etc. */ function userInfo(address _addr) view external returns ( address _referral, uint256 _referral_num, uint256 _is_supernode, uint256 _dividends, uint256 _referral_bonus, uint256 _match_bonus, uint256 _supernode_bonus,uint256 _last_payout ) { Player storage player = players[_addr]; return ( player.referral, player.referrals.length, player.is_supernode, player.dividends, player.referral_bonus, player.match_bonus, player.supernode_bonus, player.last_payout ); } /* * @dev get user info * @return pending withdraw amount,referral bonus, total deposited, total withdrawn etc. */ function userInfoTotals(address _addr) view external returns( uint256 _total_invested, uint256 _total_withdrawn, uint256 _total_community_invested, uint256 _total_match_invested, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_match_bonus, uint256 _total_supernode_bonus ) { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* get community total invested*/ uint256 total_community_invested = _getCommunityTotalInvested(_addr); return ( player.total_invested, player.total_withdrawn, total_community_invested, playerTotal.total_match_invested, playerTotal.total_dividends, playerTotal.total_referral_bonus, playerTotal.total_match_bonus, playerTotal.total_supernode_bonus ); } /* * @dev get user investment list */ function getInvestList(address _addr) view external returns( uint256[] memory ids,uint256[] memory times, uint256[] memory months, uint256[] memory amounts,uint256[] memory withdraws, uint256[] memory statuses,uint256[] memory payouts) { Player storage player = players[_addr]; PlayerDeposit[] memory deposits = _getValidInvestList(_addr); uint256[] memory _ids = new uint256[](deposits.length); uint256[] memory _times = new uint256[](deposits.length); uint256[] memory _months = new uint256[](deposits.length); uint256[] memory _amounts = new uint256[](deposits.length); uint256[] memory _withdraws = new uint256[](deposits.length); uint256[] memory _statuses = new uint256[](deposits.length); uint256[] memory _payouts = new uint256[](deposits.length); for(uint256 i = 0; i < deposits.length; i++) { PlayerDeposit memory dep = deposits[i]; _ids[i] = dep.id; _amounts[i] = dep.amount; _withdraws[i] = dep.total_withdraw; _times[i] = dep.time; _months[i] = dep.month; _statuses[i] = dep.is_crowd; _months[i] = dep.month; //get deposit current payout uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); uint256 _value = _day_payout * (to - from) / 86400; _payouts[i] = _value; } } return ( _ids, _times, _months, _amounts, _withdraws, _statuses, _payouts ); } /* * @dev get deposit valid count */ function _getValidInvestList(address _addr) view private returns(PlayerDeposit[] memory) { Player storage player = players[_addr]; uint256 resultCount; for (uint i = 0; i < player.deposits.length; i++) { if ( player.deposits[i].status == 0) { resultCount++; } } PlayerDeposit[] memory deposits = new PlayerDeposit[](resultCount); uint256 j; for(uint256 i = 0; i < player.deposits.length; i++){ if(player.deposits[i].status==0){ deposits[j] = player.deposits[i]; j++; } } return deposits; } /* * @dev get crowd period list */ function getCrowdPeriodList() view external returns(uint256[] memory ids,uint256[] memory rates, uint256[] memory limits, uint256[] memory totals) { return ( crowd_period_ids, crowd_period_rates, crowd_period_limits, total_crowd_num_periods ); } /* * @dev get invest period list */ function getInvestPeriodList(address _addr) view external returns( uint256[] memory ids,uint256[] memory months, uint256[] memory rates,uint256[] memory totals, uint256[] memory devidends,uint256[] memory user_investeds, uint256[] memory user_devidends) { PlayerTotal storage playerTotal = playerTotals[_addr]; uint256[] memory _user_period_investeds = new uint256[](4); uint256[] memory _user_period_devidends = new uint256[](4); _user_period_investeds[0] = playerTotal.total_period1_invested; _user_period_investeds[1] = playerTotal.total_period2_invested; _user_period_investeds[2] = playerTotal.total_period3_invested; _user_period_investeds[3] = playerTotal.total_period4_invested; _user_period_devidends[0] = playerTotal.total_period1_devidends; _user_period_devidends[1] = playerTotal.total_period2_devidends; _user_period_devidends[2] = playerTotal.total_period3_devidends; _user_period_devidends[3] = playerTotal.total_period4_devidends; return ( invest_period_ids, invest_period_months, invest_period_rates, invest_period_totals, invest_period_devidends, _user_period_investeds, _user_period_devidends ); } /* * @dev get supernode period list */ function getSuperNodePeriodList() view external returns(uint256[] memory ids,uint256[] memory amounts, uint256[] memory limits,uint256[] memory totals) { return ( supernode_period_ids, supernode_period_amounts, supernode_period_limits, total_supernode_num_periods ); } }
get user info return pending withdraw amount,referral,rreferral num etc./
function userInfo(address _addr) view external returns ( address _referral, uint256 _referral_num, uint256 _is_supernode, uint256 _dividends, uint256 _referral_bonus, uint256 _match_bonus, uint256 _supernode_bonus,uint256 _last_payout ) { Player storage player = players[_addr]; return ( player.referral, player.referrals.length, player.is_supernode, player.dividends, player.referral_bonus, player.match_bonus, player.supernode_bonus, player.last_payout ); }
12,749,414
./partial_match/1/0x34317e2Da45FeC7c525aCa8dAbF22CbC877128a3/sources/VidyaFLUX.sol
Maintenance balance 1% from amount (amount 1 / 100) This amount goes to Inventory Set maintenance balance to 0 Send to Inventory Send to caller Returns the amounts for UI or w/e
function feedInventory() public returns(uint256, uint256) { uint256 amount = referralBalance_[maintenanceAddress]; uint256 bonus = SafeMath.div(SafeMath.mul(amount, 1), 100); uint256 toInventory = SafeMath.sub(amount, bonus); referralBalance_[maintenanceAddress] = 0; erc20.transfer(maintenanceAddress, toInventory); erc20.transfer(msg.sender, bonus); return (toInventory, bonus); }
4,276,599
./full_match/82/0xA3F51Bb79793AC7ca38956f4928E080822814708/sources/contracts/base/vote/VoltVoterUpgradeable.sol
Add a token to a gauge/bribe as possible reward.
function registerRewardToken( address _token, address _gaugeOrBribe, uint _tokenId ) external { require(_tokenId > 0, "!token"); require(msg.sender == IERC721(ve).ownerOf(_tokenId), "!owner"); require(IVe(ve).balanceOfNFT(_tokenId) > _listingFee(), "!power"); IMultiRewardsPool(_gaugeOrBribe).registerRewardToken(_token); }
7,094,253
./full_match/137/0x0b54E16978F40540143EBaff5D69F7248d8432b5/sources/TaxDistributor.sol
if (taxes[i].taxName == taxName) {
function setBuyTax(string memory taxName, uint256 taxPercentage) public override onlyToken { bool updated; for (uint256 i = 0; i < taxes.length; i++) { if (compareStrings(taxes[i].taxName, taxName)) { taxes[i].buyTaxPercentage = taxPercentage; updated = true; } } require(updated, "could not find tax to update"); require(getBuyTax() <= 10000, "tax cannot be more than 100%"); }
4,670,294
./partial_match/1/0x16448014A29484b82E3A5A6cF254E5C563A28929/sources/ERC20.sol
Change the minter address minter_ The address of the new minter/
function setMinter(address minter_) external { require(_msgSender() == minter, "ERC20: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; }
2,845,216
// File: contracts\core\nameVerifiers\IIdeaTokenNameVerifier.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.9; /** * @title IIdeaTokenNameVerifier * @author Alexander Schlindwein * * Interface for token name verifiers */ interface IIdeaTokenNameVerifier { function verifyTokenName(string calldata name) external pure returns (bool); } // File: contracts\core\nameVerifiers\TwitterHandleNameVerifier.sol /** * @title TwitterHandleNameVerifier * @author Alexander Schlindwein * * Verifies a string to be a Twitter handle: @ followed by 1-15 letters or numbers including "_". All lower-case. */ contract TwitterHandleNameVerifier is IIdeaTokenNameVerifier { /** * Verifies whether a string matches the required format * * @param name The input string (Twitter handle) * * @return Bool; True=matches, False=does not match */ function verifyTokenName(string calldata name) external pure override returns (bool) { bytes memory b = bytes(name); if(b.length < 2 || b.length > 16) { return false; } if(b[0] != 0x40) { // @ return false; } for(uint i = 1; i < b.length; i++) { bytes1 char = b[i]; if (!(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x5F)) { //_ return false; } } return true; } }
Verifies whether a string matches the required format name The input string (Twitter handle) return Bool; True=matches, False=does not match/
function verifyTokenName(string calldata name) external pure override returns (bool) { bytes memory b = bytes(name); if(b.length < 2 || b.length > 16) { return false; } return false; }
13,726,862
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IUniswapV2Router02.sol"; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; contract Multiswap { using SafeMath for uint256; using SafeERC20 for IERC20; // WETH Address address private immutable WETH; // Uniswap Router for swaps IUniswapV2Router02 private immutable uniswapRouter; // Referral data mapping (address => bool) private referrers; mapping (address => uint256) private referralFees; // Data struct struct ContractData { uint160 owner; uint16 swapFeeBase; uint16 swapFeeToken; uint16 referralFee; uint16 maxFee; } ContractData private data; // Modifier for only owner functions modifier onlyOwner { require(msg.sender == address(data.owner), "Not allowed"); _; } /** * @dev Constructor sets values for Uniswap, WETH, and fee data * * These values are the immutable state values for Uniswap and WETH. * */ constructor() { uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); data.owner = uint160(msg.sender); // add extra two digits to percent for accuracy (30 = 0.3) data.swapFeeBase = uint16(30); // 0.3% data.swapFeeToken = uint16(20); // 0.2% per token data.referralFee = uint16(4500); // 45% for referrals data.maxFee = uint16(150); // 1.5% max fee // Add standard referrers referrers[address(this)] = true; referrers[address(0x1190074795DAD0E61b61270De48e108427f8f817)] = true; } /** * @dev Enables receiving ETH with no function call */ receive() external payable {} fallback() external payable {} /** * @dev Checks and returns expected output fom ETH swap. */ function checkOutputsETH( address[] memory _tokens, uint256[] memory _percent, uint256 _total ) external view returns (address[] memory, uint256[] memory, uint256) { require(_tokens.length == _percent.length); uint256 _totalPercent = 0; (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(_total, _tokens.length); uint256[] memory _outputAmount = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { _totalPercent += _percent[i]; (_outputAmount[i],) = calcOutputEth( _tokens[i], valueToSend.mul(_percent[i]).div(100) ); } require(_totalPercent == 100); return (_tokens, _outputAmount, feeAmount); } /** * @dev Checks and returns expected output from token swap. */ function checkOutputsToken( address[] memory _tokens, uint256[] memory _percent, address _base, uint256 _total ) external view returns (address[] memory, uint256[] memory) { require(_tokens.length == _percent.length); uint256 _totalPercent = 0; uint256[] memory _outputAmount = new uint256[](_tokens.length); address[] memory path = new address[](3); path[0] = _base; path[1] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { _totalPercent += _percent[i]; path[2] = _tokens[i]; uint256[] memory expected = uniswapRouter.getAmountsOut(_total.mul(_percent[i]).div(100), path); _outputAmount[i] = uint256(expected[1]); } require(_totalPercent == 100); return (_tokens, _outputAmount); } /** * @dev Checks and returns ETH value of token amount. */ function checkTokenValueETH(address _token, uint256 _amount) public view returns (uint256) { address[] memory path = new address[](2); path[0] = _token; path[1] = WETH; uint256[] memory expected = uniswapRouter.getAmountsOut(_amount, path); return expected[1]; } /** * @dev Checks and returns ETH value of portfolio. */ function checkAllValue(address[] memory _tokens, uint256[] memory _amounts) public view returns (uint256) { uint256 totalValue; for (uint i = 0; i < _tokens.length; i++) { totalValue += checkTokenValueETH(_tokens[i], _amounts[i]); } return totalValue; } /** * @dev Internal function to calculate the output from one ETH swap. */ function calcOutputEth(address _token, uint256 _value) internal view returns (uint256, address[] memory) { address[] memory path = new address[](2); path[0] = WETH; path[1] = _token; uint256[] memory expected = uniswapRouter.getAmountsOut(_value, path); return (expected[1], path); } /** * @dev Internal function to calculate the output from one token swap. */ function calcOutputToken(address[] memory _path, uint256 _value) internal view returns (uint256[] memory expected) { expected = uniswapRouter.getAmountsOut(_value, _path); return expected; } /** * @dev Execute ETH swap for each token in portfolio. */ function makeETHSwap(address[] memory _tokens, uint256[] memory _percent, address _referrer) external payable returns (uint256[] memory) { (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(msg.value, _tokens.length); uint256 totalPercent; uint256[] memory outputs = new uint256[](_tokens.length); address[] memory path = new address[](2); path[0] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { totalPercent += _percent[i]; require(totalPercent <= 100, 'Exceeded 100%'); path[1] = _tokens[i]; uint256 swapVal = valueToSend.mul(_percent[i]).div(100); uint256[] memory expected = uniswapRouter.getAmountsOut(swapVal, path); uint256[] memory out = uniswapRouter.swapExactETHForTokens{value: swapVal}( expected[1], path, msg.sender, block.timestamp + 1200 ); outputs[i] = out[1]; } require(totalPercent == 100, 'Percent not 100'); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); (bool sent, ) = _referrer.call{value: referralFee}(""); require(sent, 'Failed to send referral fee'); } return outputs; } /** * @dev Execute token swap for each token in portfolio. */ function makeTokenSwap( address[] memory _tokens, uint256[] memory _percent, address _base, uint256 _total) external returns (uint256[] memory) { IERC20 token = IERC20(_base); uint256 totalPercent = 0; uint256[] memory outputs = new uint256[](_tokens.length); token.safeTransferFrom(msg.sender, address(this), _total); require(token.approve(address(uniswapRouter), _total), 'Uniswap approval failed'); address[] memory path = new address[](3); path[0] = _base; path[1] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { totalPercent += _percent[i]; require(totalPercent <= 100, 'Exceeded 100'); path[2] = _tokens[i]; uint256 swapVal = _total.mul(_percent[i]).div(100); uint256[] memory expected = uniswapRouter.getAmountsOut(swapVal, path); uint256[] memory out = uniswapRouter.swapExactTokensForTokens( expected[0], expected[1], path, msg.sender, block.timestamp + 1200 ); outputs[i] = out[1]; } require(totalPercent == 100, 'Percent not 100'); return outputs; } /** * @dev Swap tokens for ETH */ function makeTokenSwapForETH( address[] memory _tokens, uint256[] memory _amounts, address _referrer ) external payable returns (uint256) { address[] memory path = new address[](2); path[1] = WETH; uint256 totalOutput; for (uint i = 0; i < _tokens.length; i++) { path[0] = _tokens[i]; IERC20 token = IERC20(_tokens[i]); token.transferFrom(msg.sender, address(this), _amounts[i]); token.approve(address(uniswapRouter), _amounts[i]); uint256[] memory expected = uniswapRouter.getAmountsOut(_amounts[i], path); uint256[] memory swapOutput = uniswapRouter.swapExactTokensForETH(expected[0], expected[1], path, address(this), block.timestamp + 1200); totalOutput = totalOutput.add(swapOutput[1]); } (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(totalOutput, _tokens.length); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); (bool sent, ) = _referrer.call{value: referralFee}(""); require(sent, 'Failed to send referral fee'); } (bool delivered, ) = msg.sender.call{value: valueToSend}(""); require(delivered, 'Failed to send swap output'); return valueToSend; } /** * @dev Apply fee to total value amount for ETH swap. */ function applyFeeETH(uint256 _amount, uint256 _numberOfTokens) private view returns (uint256 valueToSend, uint256 feeAmount) { uint256 feePercent = _numberOfTokens.mul(data.swapFeeToken); feePercent -= data.swapFeeToken; feePercent += data.swapFeeBase; feeAmount = _amount.mul(feePercent).div(10000); valueToSend = _amount.sub(feeAmount); return (valueToSend, feeAmount); } /** * @dev Take referral fee and distribute */ function takeReferralFee(uint256 _fee, address _referrer) internal returns (uint256) { require(referrers[_referrer], 'Not signed up as referrer'); uint256 referralFee = _fee.mul(data.referralFee).div(10000); referralFees[_referrer] = referralFees[_referrer].add(referralFee); return referralFee; } /** * @dev Owner only function to update contract fees. */ function updateFee( uint16 _newFeeBase, uint16 _newFeeToken, uint16 _newFeeReferral, uint16 _newMaxFee ) public onlyOwner returns (bool) { data.swapFeeBase = _newFeeBase; data.swapFeeToken = _newFeeToken; data.referralFee = _newFeeReferral; data.maxFee = _newMaxFee; return true; } /** * @dev Returns current app fees. */ function getCurrentFee() external view returns ( uint16, uint16, uint16, uint16 ) { return (data.swapFeeBase, data.swapFeeToken, data.referralFee, data.maxFee); } /** * @dev Owner only function to change contract owner. */ function changeOwner(address newOwner) external onlyOwner returns (bool) { data.owner = uint160(newOwner); return true; } /** * @dev Owner only function to change contract owner. */ function addReferrer(address _referrer) external onlyOwner returns (bool) { referrers[_referrer] = true; return true; } /** * @dev Owner only function to change contract owner. */ function removeReferrer(address _referrer) external onlyOwner returns (bool) { referrers[_referrer] = false; return true; } /** * @dev Return owner address */ function getOwner() external view returns (address) { return address(data.owner); } /** * @dev Function to see referral balancees */ function getReferralFees(address _referrer) external view returns (uint256) { return referralFees[_referrer]; } /** * @dev Owner only function to retreive ETH fees */ function retrieveEthFees() external onlyOwner { (bool sent, ) = address(data.owner).call{value: address(this).balance}(""); require(sent, 'Transfer failed'); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; } }
Internal function to calculate the output from one token swap./
function calcOutputToken(address[] memory _path, uint256 _value) internal view returns (uint256[] memory expected) { expected = uniswapRouter.getAmountsOut(_value, _path); return expected; }
548,217
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './AbstractERC1155Factory.sol'; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract OmniPass is AbstractERC1155Factory, ReentrancyGuard { // ======== ERC1155 Token Id ========= uint256 constant MINT_PASS_ID = 0; // ======== Supply ========= uint256 public constant MAX_MINTS_PER_TX = 20; uint256 public constant MAX_MINTS_PER_ADDRESS = 100; uint256 public maxSupply = 20000; // ======== Claim Tracking ========= mapping(address => uint256) private addressToMintCount; // ======== Sale Status ========= bool public saleIsActive = false; // ======== Redeem Contract ========= address public redeemContract; bool public redeemContractSet; bool public redeemEnabled; // ======== Cost ========= uint256 public constant TOKEN_PRICE_ETH = 0.1 ether; // ======== Fund Management ========= // Omniya Wallet address public withdrawalAddress = 0x0FE7be1Ce87D153AdFBf1573E3Db77bbD9E0f549; constructor(string memory _name, string memory _symbol, string memory _uri) ERC1155(_uri) { name_ = _name; symbol_ = _symbol; } // ======== Mint ========= /// @notice Mint tokens /// @param amount Quantity of tokens to mint function mint(uint256 amount) public payable nonReentrant { require(totalSupply(0) + amount <= maxSupply, "Exceeds max token supply!"); require(saleIsActive, "Sale is not active!"); require(amount <= MAX_MINTS_PER_TX, "Exceeds max mint per tx!"); require(addressToMintCount[msg.sender] + amount <= MAX_MINTS_PER_ADDRESS, "Exceeds max mint per address!"); transferFunds(amount); _mint(msg.sender, MINT_PASS_ID, amount, ""); addressToMintCount[msg.sender] += amount; } /// @notice Allows owner to mint team tokens /// @param to The address to send the minted tokens to /// @param amount The amount of tokens to mint function mintTeamTokens(address to, uint256 amount) public onlyOwner { require(totalSupply(0) + amount <= maxSupply, "Exceeds max token supply!"); _mint(to, MINT_PASS_ID, amount, ""); } // ======== Redeem Management ========= /// @notice Allows mint pass owner to burn a mint pass. Can only be called from Redeem contract /// @param account The address redeeming the mint passes /// @param amount The amount of mint passes to burn function burnFromRedeem(address account, uint256 amount) external { require(redeemContract == msg.sender, "Burnable: Only allowed from redeemable contract"); require(redeemEnabled, "Burn from redeem disabled!"); _burn(account, MINT_PASS_ID, amount); } /// @notice Allows owner to set the redeem contract /// @param _redeemContract The address of the redeem contract function setRedeemContract(address _redeemContract) external onlyOwner { redeemContract = _redeemContract; redeemContractSet = true; } /// @notice Allows toggles the redeem feature function toggleRedeem() external onlyOwner { redeemEnabled = !redeemEnabled; } // ======== Metadata ========= function setURI(string memory _baseURI) external onlyOwner { _setURI(_baseURI); } // ======== State Management ========= function flipSaleStatus() public onlyOwner { saleIsActive = !saleIsActive; } // ======== Token Supply Management========= function mintCount(address _address) external view returns (uint) { return addressToMintCount[_address]; } /// @notice Decrease max token supply /// @param newMaxTokenSupply maximum token supply function decreaseTokenSupply(uint256 newMaxTokenSupply) external onlyOwner { require(maxSupply > newMaxTokenSupply, "Max token supply can only be decreased!"); require(newMaxTokenSupply >= totalSupply(0), "Max token supply has to be greeather than or equal to total supply!"); maxSupply = newMaxTokenSupply; } // ======== Withdraw ========= /// @notice Transfers funds to withdrawal address /// @param qty Quantity of tokens to purchase function transferFunds(uint256 qty) private { if(msg.value == qty * TOKEN_PRICE_ETH) { (bool success, ) = payable(withdrawalAddress).call{value: qty * TOKEN_PRICE_ETH}(""); require(success, "Transfer failed!"); } else { revert("Invalid payment!"); } } /// @notice Sets a new withdrawal address /// @param newWithdrawalAddress New withdrawal address function setWithdrawalAddress(address newWithdrawalAddress) public onlyOwner { withdrawalAddress = newWithdrawalAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol'; abstract contract AbstractERC1155Factory is ERC1155Supply, ERC1155Burnable, Ownable { string public name_; string public symbol_; function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
======== State Management =========
function flipSaleStatus() public onlyOwner { saleIsActive = !saleIsActive; }
6,145,487
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. 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; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } library UrlStr { // generate url by tokenId // baseUrl must end with 00000000 function generateUrl(string url,uint256 _tokenId) internal pure returns (string _url){ _url = url; bytes memory _tokenURIBytes = bytes(_url); uint256 base_len = _tokenURIBytes.length - 1; _tokenURIBytes[base_len - 7] = byte(48 + _tokenId / 10000000 % 10); _tokenURIBytes[base_len - 6] = byte(48 + _tokenId / 1000000 % 10); _tokenURIBytes[base_len - 5] = byte(48 + _tokenId / 100000 % 10); _tokenURIBytes[base_len - 4] = byte(48 + _tokenId / 10000 % 10); _tokenURIBytes[base_len - 3] = byte(48 + _tokenId / 1000 % 10); _tokenURIBytes[base_len - 2] = byte(48 + _tokenId / 100 % 10); _tokenURIBytes[base_len - 1] = byte(48 + _tokenId / 10 % 10); _tokenURIBytes[base_len - 0] = byte(48 + _tokenId / 1 % 10); } } /** if a ERC721 item want to mount to avatar, it must to inherit this. */ interface AvatarChildService { /** @dev if you want your contract become a avatar child, please let your contract inherit this interface @param _tokenId1 first child token id @param _tokenId2 second child token id @return true will unmount first token before mount ,false will directly mount child */ function compareItemSlots(uint256 _tokenId1, uint256 _tokenId2) external view returns (bool _res); } interface AvatarService { function updateAvatarInfo(address _owner, uint256 _tokenId, string _name, uint256 _dna) external; function createAvatar(address _owner, string _name, uint256 _dna) external returns(uint256); function getMountTokenIds(address _owner,uint256 _tokenId, address _avatarItemAddress) external view returns(uint256[]); function getAvatarInfo(uint256 _tokenId) external view returns (string _name, uint256 _dna); function getOwnedTokenIds(address _owner) external view returns(uint256[] _tokenIds); } interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } interface ERC721 /* is ERC165 */ { /// @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) external 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) external 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) external; /// @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) external; /// @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) external; /// @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) external 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) external view returns (bool); } /// Note: the ERC-165 identifier for this interface is 0x780e9d63. interface ERC721Enumerable /* is ERC721 */ { /// @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() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev 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 The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// Note: the ERC-165 identifier for this interface is 0x5b5e139f. interface ERC721Metadata /* is ERC721 */ { /// @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); } /// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. interface 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) external returns(bytes4); } /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } /** * @title BitGuildAccessAdmin * @dev Allow two roles: 'owner' or 'operator' * - owner: admin/superuser (e.g. with financial rights) * - operator: can update configurations */ contract BitGuildAccessAdmin { address public owner; address[] public operators; uint public MAX_OPS = 20; // Default maximum number of operators allowed mapping(address => bool) public isOperator; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event OperatorAdded(address operator); event OperatorRemoved(address operator); // @dev The BitGuildAccessAdmin constructor: sets owner 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 Throws if called by any non-operator account. Owner has all ops rights. modifier onlyOperator { require( isOperator[msg.sender] || msg.sender == owner, "Permission denied. Must be an operator or the 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), "Invalid new owner address." ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /** * @dev Allows the current owner or operators to add operators * @param _newOperator New operator address */ function addOperator(address _newOperator) public onlyOwner { require( _newOperator != address(0), "Invalid new operator address." ); // Make sure no dups require( !isOperator[_newOperator], "New operator exists." ); // Only allow so many ops require( operators.length < MAX_OPS, "Overflow." ); operators.push(_newOperator); isOperator[_newOperator] = true; emit OperatorAdded(_newOperator); } /** * @dev Allows the current owner or operators to remove operator * @param _operator Address of the operator to be removed */ function removeOperator(address _operator) public onlyOwner { // Make sure operators array is not empty require( operators.length > 0, "No operator." ); // Make sure the operator exists require( isOperator[_operator], "Not an operator." ); // Manual array manipulation: // - replace the _operator with last operator in array // - remove the last item from array address lastOperator = operators[operators.length - 1]; for (uint i = 0; i < operators.length; i++) { if (operators[i] == _operator) { operators[i] = lastOperator; } } operators.length -= 1; // remove the last element isOperator[_operator] = false; emit OperatorRemoved(_operator); } // @dev Remove ALL operators function removeAllOps() public onlyOwner { for (uint i = 0; i < operators.length; i++) { isOperator[operators[i]] = false; } operators.length = 0; } } contract BitGuildAccessAdminExtend is BitGuildAccessAdmin { event FrozenFunds(address target, bool frozen); bool public isPaused = false; mapping(address => bool) frozenAccount; modifier whenNotPaused { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function doPause() external whenNotPaused onlyOwner { isPaused = true; } function doUnpause() external whenPaused onlyOwner { isPaused = false; } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } } interface ERC998ERC721TopDown { event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId); event TransferChild(uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId); // gets the address and token that owns the supplied tokenId. isParent says if parentTokenId is a parent token or not. function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent); function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (uint256 parentTokenId, uint256 isParent); function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4); function onERC998Removed(address _operator, address _toContract, uint256 _childTokenId, bytes _data) external; function transferChild(address _to, address _childContract, uint256 _childTokenId) external; function safeTransferChild(address _to, address _childContract, uint256 _childTokenId) external; function safeTransferChild(address _to, address _childContract, uint256 _childTokenId, bytes _data) external; // getChild function enables older contracts like cryptokitties to be transferred into a composable // The _childContract must approve this contract. Then getChild can be called. function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external; } interface ERC998ERC721TopDownEnumerable { function totalChildContracts(uint256 _tokenId) external view returns(uint256); function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract); function totalChildTokens(uint256 _tokenId, address _childContract) external view returns(uint256); function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId); } interface ERC998ERC20TopDown { event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc223Contract, uint256 _value); event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc223Contract, uint256 _value); function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent); function tokenFallback(address _from, uint256 _value, bytes _data) external; function balanceOfERC20(uint256 _tokenId, address __erc223Contract) external view returns(uint256); function transferERC20(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value) external; function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external; function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) external; } interface ERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns(uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns(address); } interface ERC20AndERC223 { function transferFrom(address _from, address _to, uint _value) external returns (bool success); function transfer(address to, uint value) external returns (bool success); function transfer(address to, uint value, bytes data) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); } contract ComposableTopDown is ERC721, ERC998ERC721TopDown, ERC998ERC721TopDownEnumerable, ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable, BitGuildAccessAdminExtend{ // tokenOwnerOf.selector; uint256 constant TOKEN_OWNER_OF = 0x89885a59; uint256 constant OWNER_OF_CHILD = 0xeadb80b8; // tokenId => token owner mapping (uint256 => address) internal tokenIdToTokenOwner; // root token owner address => (tokenId => approved address) mapping (address => mapping (uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress; // token owner address => token count mapping (address => uint256) internal tokenOwnerToTokenCount; // token owner => (operator address => bool) mapping (address => mapping (address => bool)) internal tokenOwnerToOperators; //from zepellin ERC721Receiver.sol //old version bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; //new version bytes4 constant ERC721_RECEIVED_NEW = 0x150b7a02; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ bytes4 constant InterfaceId_ERC998 = 0x520bdcbe; //InterfaceId_ERC998 = bytes4(keccak256('tokenOwnerOf(uint256)')) ^ // bytes4(keccak256('ownerOfChild(address,uint256)')) ^ // bytes4(keccak256('onERC721Received(address,address,uint256,bytes)')) ^ // bytes4(keccak256('onERC998RemovedChild(address,address,uint256,bytes)')) ^ // bytes4(keccak256('transferChild(address,address,uint256)')) ^ // bytes4(keccak256('safeTransferChild(address,address,uint256)')) ^ // bytes4(keccak256('safeTransferChild(address,address,uint256,bytes)')) ^ // bytes4(keccak256('getChild(address,address,uint256,uint256)')); //////////////////////////////////////////////////////// // ERC721 implementation //////////////////////////////////////////////////////// function _mint(address _to,uint256 _tokenId) internal whenNotPaused { tokenIdToTokenOwner[_tokenId] = _to; tokenOwnerToTokenCount[_to]++; emit Transfer(address(0), _to, _tokenId); } function isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) { tokenOwner = tokenIdToTokenOwner[_tokenId]; require(tokenOwner != address(0)); if(tokenOwner == address(this)) { (parentTokenId, isParent) = ownerOfChild(address(this), _tokenId); } else { bool callSuccess; // 0xeadb80b8 == ownerOfChild(address,uint256) bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId); assembly { callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40) if callSuccess { parentTokenId := mload(calldata) isParent := mload(add(calldata,0x20)) } } if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) { isParent = TOKEN_OWNER_OF << 8 | uint8(isParent); } else { isParent = TOKEN_OWNER_OF << 8; parentTokenId = 0; } } return (tokenOwner, parentTokenId, isParent); } function ownerOf(uint256 _tokenId) external view returns (address rootOwner) { return _ownerOf(_tokenId); } // returns the owner at the top of the tree of composables function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) { rootOwner = tokenIdToTokenOwner[_tokenId]; require(rootOwner != address(0)); uint256 isParent = 1; bool callSuccess; bytes memory calldata; while(uint8(isParent) > 0) { if(rootOwner == address(this)) { (_tokenId, isParent) = ownerOfChild(address(this), _tokenId); if(uint8(isParent) > 0) { rootOwner = tokenIdToTokenOwner[_tokenId]; } } else { if(isContract(rootOwner)) { //0x89885a59 == "tokenOwnerOf(uint256)" calldata = abi.encodeWithSelector(0x89885a59, _tokenId); assembly { callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60) if callSuccess { rootOwner := mload(calldata) _tokenId := mload(add(calldata,0x20)) isParent := mload(add(calldata,0x40)) } } if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) { //0x6352211e == "_ownerOf(uint256)" calldata = abi.encodeWithSelector(0x6352211e, _tokenId); assembly { callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20) if callSuccess { rootOwner := mload(calldata) } } require(callSuccess, "rootOwnerOf failed"); isParent = 0; } } else { isParent = 0; } } } return rootOwner; } function balanceOf(address _tokenOwner) external view returns (uint256) { require(_tokenOwner != address(0)); return tokenOwnerToTokenCount[_tokenOwner]; } function approve(address _approved, uint256 _tokenId) external whenNotPaused { address tokenOwner = tokenIdToTokenOwner[_tokenId]; address rootOwner = _ownerOf(_tokenId); require(tokenOwner != address(0)); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved; emit Approval(rootOwner, _approved, _tokenId); } function getApproved(uint256 _tokenId) external view returns (address) { address rootOwner = _ownerOf(_tokenId); return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; } function setApprovalForAll(address _operator, bool _approved) external whenNotPaused { require(_operator != address(0)); tokenOwnerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function isApprovedForAll(address _owner, address _operator ) external view returns (bool) { require(_owner != address(0)); require(_operator != address(0)); return tokenOwnerToOperators[_owner][_operator]; } function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused { require(!frozenAccount[_from]); require(!frozenAccount[_to]); // tokenIdToTokenOwner[_tokenId] = _to; // tokenOwnerToTokenCount[_to]++; address tokenOwner = tokenIdToTokenOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); address rootOwner = _ownerOf(_tokenId); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); // clear approval if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; } // remove and transfer token if(_from != _to) { assert(tokenOwnerToTokenCount[_from] > 0); tokenOwnerToTokenCount[_from]--; tokenIdToTokenOwner[_tokenId] = _to; tokenOwnerToTokenCount[_to]++; } emit Transfer(_from, _to, _tokenId); if(isContract(_from)) { //0x0da719ec == "onERC998Removed(address,address,uint256,bytes)" bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,""); assembly { let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0) } } } function transferFrom(address _from, address _to, uint256 _tokenId) external { _transfer(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { _transfer(_from, _to, _tokenId); if(isContract(_to)) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, ""); require(retval == ERC721_RECEIVED_OLD); } } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external { _transfer(_from, _to, _tokenId); if(isContract(_to)) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == ERC721_RECEIVED_OLD); } } //////////////////////////////////////////////////////// // ERC998ERC721 and ERC998ERC721Enumerable implementation //////////////////////////////////////////////////////// // tokenId => child contract mapping(uint256 => address[]) internal childContracts; // tokenId => (child address => contract index+1) mapping(uint256 => mapping(address => uint256)) internal childContractIndex; // tokenId => (child address => array of child tokens) mapping(uint256 => mapping(address => uint256[])) internal childTokens; // tokenId => (child address => (child token => child index+1) mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal childTokenIndex; // child address => childId => tokenId mapping(address => mapping(uint256 => uint256)) internal childTokenOwner; function onERC998Removed(address _operator, address _toContract, uint256 _childTokenId, bytes _data) external { uint256 tokenId = childTokenOwner[msg.sender][_childTokenId]; _removeChild(tokenId, msg.sender, _childTokenId); } function safeTransferChild(address _to, address _childContract, uint256 _childTokenId) external { (uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId); require(uint8(isParent) > 0); address tokenOwner = tokenIdToTokenOwner[tokenId]; require(_to != address(0)); address rootOwner = _ownerOf(tokenId); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); _removeChild(tokenId, _childContract, _childTokenId); ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId); emit TransferChild(tokenId, _to, _childContract, _childTokenId); } function safeTransferChild(address _to, address _childContract, uint256 _childTokenId, bytes _data) external { (uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId); require(uint8(isParent) > 0); address tokenOwner = tokenIdToTokenOwner[tokenId]; require(_to != address(0)); address rootOwner = _ownerOf(tokenId); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); _removeChild(tokenId, _childContract, _childTokenId); ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId, _data); emit TransferChild(tokenId, _to, _childContract, _childTokenId); } function transferChild(address _to, address _childContract, uint256 _childTokenId) external { _transferChild(_to, _childContract,_childTokenId); } function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external { _getChild(_from, _tokenId, _childContract,_childTokenId); } function onERC721Received(address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) { require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to."); require(isContract(msg.sender), "msg.sender is not a contract."); /************************************** * TODO move to library **************************************/ // convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes uint256 tokenId; assembly { // new onERC721Received //tokenId := calldataload(164) tokenId := calldataload(132) } if(_data.length < 32) { tokenId = tokenId >> 256 - _data.length * 8; } //END TODO //require(this == ERC721Basic(msg.sender)._ownerOf(_childTokenId), "This contract does not own the child token."); _receiveChild(_from, tokenId, msg.sender, _childTokenId); //cause out of gas error if circular ownership _ownerOf(tokenId); return ERC721_RECEIVED_OLD; } function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) { require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to."); require(isContract(msg.sender), "msg.sender is not a contract."); /************************************** * TODO move to library **************************************/ // convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes uint256 tokenId; assembly { // new onERC721Received tokenId := calldataload(164) //tokenId := calldataload(132) } if(_data.length < 32) { tokenId = tokenId >> 256 - _data.length * 8; } //END TODO //require(this == ERC721Basic(msg.sender)._ownerOf(_childTokenId), "This contract does not own the child token."); _receiveChild(_from, tokenId, msg.sender, _childTokenId); //cause out of gas error if circular ownership _ownerOf(tokenId); return ERC721_RECEIVED_NEW; } function _transferChild(address _to, address _childContract, uint256 _childTokenId) internal { (uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId); require(uint8(isParent) > 0); address tokenOwner = tokenIdToTokenOwner[tokenId]; require(_to != address(0)); address rootOwner = _ownerOf(tokenId); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); _removeChild(tokenId, _childContract, _childTokenId); //this is here to be compatible with cryptokitties and other old contracts that require being owner and approved // before transferring. //does not work with current standard which does not allow approving self, so we must let it fail in that case. //0x095ea7b3 == "approve(address,uint256)" bytes memory calldata = abi.encodeWithSelector(0x095ea7b3, this, _childTokenId); assembly { let success := call(gas, _childContract, 0, add(calldata, 0x20), mload(calldata), calldata, 0) } ERC721(_childContract).transferFrom(this, _to, _childTokenId); emit TransferChild(tokenId, _to, _childContract, _childTokenId); } // this contract has to be approved first in _childContract function _getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal { _receiveChild(_from, _tokenId, _childContract, _childTokenId); require( _from == msg.sender || ERC721(_childContract).isApprovedForAll(_from, msg.sender) || ERC721(_childContract).getApproved(_childTokenId) == msg.sender); ERC721(_childContract).transferFrom(_from, this, _childTokenId); //cause out of gas error if circular ownership _ownerOf(_tokenId); } function _receiveChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused { require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist."); require(childTokenIndex[_tokenId][_childContract][_childTokenId] == 0, "Cannot receive child token because it has already been received."); uint256 childTokensLength = childTokens[_tokenId][_childContract].length; if(childTokensLength == 0) { childContractIndex[_tokenId][_childContract] = childContracts[_tokenId].length; childContracts[_tokenId].push(_childContract); } childTokens[_tokenId][_childContract].push(_childTokenId); childTokenIndex[_tokenId][_childContract][_childTokenId] = childTokensLength + 1; childTokenOwner[_childContract][_childTokenId] = _tokenId; emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId); } function _removeChild(uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused { uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][_childTokenId]; require(tokenIndex != 0, "Child token not owned by token."); // remove child token uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length-1; uint256 lastToken = childTokens[_tokenId][_childContract][lastTokenIndex]; //if(_childTokenId == lastToken) { childTokens[_tokenId][_childContract][tokenIndex-1] = lastToken; childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex; //} childTokens[_tokenId][_childContract].length--; delete childTokenIndex[_tokenId][_childContract][_childTokenId]; delete childTokenOwner[_childContract][_childTokenId]; // remove contract if(lastTokenIndex == 0) { uint256 lastContractIndex = childContracts[_tokenId].length - 1; address lastContract = childContracts[_tokenId][lastContractIndex]; if(_childContract != lastContract) { uint256 contractIndex = childContractIndex[_tokenId][_childContract]; childContracts[_tokenId][contractIndex] = lastContract; childContractIndex[_tokenId][lastContract] = contractIndex; } childContracts[_tokenId].length--; delete childContractIndex[_tokenId][_childContract]; } } function ownerOfChild(address _childContract, uint256 _childTokenId) public view returns (uint256 parentTokenId, uint256 isParent) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; if(parentTokenId == 0 && childTokenIndex[parentTokenId][_childContract][_childTokenId] == 0) { return (0, OWNER_OF_CHILD << 8); } return (parentTokenId, OWNER_OF_CHILD << 8 | 1); } function childExists(address _childContract, uint256 _childTokenId) external view returns (bool) { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; return childTokenIndex[tokenId][_childContract][_childTokenId] != 0; } function totalChildContracts(uint256 _tokenId) external view returns(uint256) { return childContracts[_tokenId].length; } function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract) { require(_index < childContracts[_tokenId].length, "Contract address does not exist for this token and index."); return childContracts[_tokenId][_index]; } function totalChildTokens(uint256 _tokenId, address _childContract) external view returns(uint256) { return childTokens[_tokenId][_childContract].length; } function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId) { require(_index < childTokens[_tokenId][_childContract].length, "Token does not own a child token at contract address and index."); return childTokens[_tokenId][_childContract][_index]; } //////////////////////////////////////////////////////// // ERC998ERC223 and ERC998ERC223Enumerable implementation //////////////////////////////////////////////////////// // tokenId => token contract mapping(uint256 => address[]) erc223Contracts; // tokenId => (token contract => token contract index) mapping(uint256 => mapping(address => uint256)) erc223ContractIndex; // tokenId => (token contract => balance) mapping(uint256 => mapping(address => uint256)) erc223Balances; function balanceOfERC20(uint256 _tokenId, address _erc223Contract) external view returns(uint256) { return erc223Balances[_tokenId][_erc223Contract]; } function removeERC223(uint256 _tokenId, address _erc223Contract, uint256 _value) private whenNotPaused { if(_value == 0) { return; } uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract]; require(erc223Balance >= _value, "Not enough token available to transfer."); uint256 newERC223Balance = erc223Balance - _value; erc223Balances[_tokenId][_erc223Contract] = newERC223Balance; if(newERC223Balance == 0) { uint256 lastContractIndex = erc223Contracts[_tokenId].length - 1; address lastContract = erc223Contracts[_tokenId][lastContractIndex]; if(_erc223Contract != lastContract) { uint256 contractIndex = erc223ContractIndex[_tokenId][_erc223Contract]; erc223Contracts[_tokenId][contractIndex] = lastContract; erc223ContractIndex[_tokenId][lastContract] = contractIndex; } erc223Contracts[_tokenId].length--; delete erc223ContractIndex[_tokenId][_erc223Contract]; } } function transferERC20(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value) external { address tokenOwner = tokenIdToTokenOwner[_tokenId]; require(_to != address(0)); address rootOwner = _ownerOf(_tokenId); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); removeERC223(_tokenId, _erc223Contract, _value); require(ERC20AndERC223(_erc223Contract).transfer(_to, _value), "ERC20 transfer failed."); emit TransferERC20(_tokenId, _to, _erc223Contract, _value); } // implementation of ERC 223 function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external { address tokenOwner = tokenIdToTokenOwner[_tokenId]; require(_to != address(0)); address rootOwner = _ownerOf(_tokenId); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender || tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]); removeERC223(_tokenId, _erc223Contract, _value); require(ERC20AndERC223(_erc223Contract).transfer(_to, _value, _data), "ERC223 transfer failed."); emit TransferERC20(_tokenId, _to, _erc223Contract, _value); } // this contract has to be approved first by _erc223Contract function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) public { bool allowed = _from == msg.sender; if(!allowed) { uint256 remaining; // 0xdd62ed3e == allowance(address,address) bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e,_from,msg.sender); bool callSuccess; assembly { callSuccess := staticcall(gas, _erc223Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20) if callSuccess { remaining := mload(calldata) } } require(callSuccess, "call to allowance failed"); require(remaining >= _value, "Value greater than remaining"); allowed = true; } require(allowed, "not allowed to getERC20"); erc223Received(_from, _tokenId, _erc223Contract, _value); require(ERC20AndERC223(_erc223Contract).transferFrom(_from, this, _value), "ERC20 transfer failed."); } function erc223Received(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) private { require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist."); if(_value == 0) { return; } uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract]; if(erc223Balance == 0) { erc223ContractIndex[_tokenId][_erc223Contract] = erc223Contracts[_tokenId].length; erc223Contracts[_tokenId].push(_erc223Contract); } erc223Balances[_tokenId][_erc223Contract] += _value; emit ReceivedERC20(_from, _tokenId, _erc223Contract, _value); } // used by ERC 223 function tokenFallback(address _from, uint256 _value, bytes _data) external { require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the token to."); require(isContract(msg.sender), "msg.sender is not a contract"); /************************************** * TODO move to library **************************************/ // convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes uint256 tokenId; assembly { tokenId := calldataload(132) } if(_data.length < 32) { tokenId = tokenId >> 256 - _data.length * 8; } //END TODO erc223Received(_from, tokenId, msg.sender, _value); } function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns(address) { require(_index < erc223Contracts[_tokenId].length, "Contract address does not exist for this token and index."); return erc223Contracts[_tokenId][_index]; } function totalERC20Contracts(uint256 _tokenId) external view returns(uint256) { return erc223Contracts[_tokenId].length; } } contract ERC998TopDownToken is SupportsInterfaceWithLookup, ERC721Enumerable, ERC721Metadata, ComposableTopDown { using SafeMath for uint256; bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(InterfaceId_ERC998); } modifier existsToken(uint256 _tokenId){ address owner = tokenIdToTokenOwner[_tokenId]; require(owner != address(0), "This tokenId is invalid"); _; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return "Bitizen"; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return "BTZN"; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) external view existsToken(_tokenId) returns (string) { return ""; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(address(0) != _owner); require(_index < tokenOwnerToTokenCount[_owner]); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) existsToken(_tokenId) internal { tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address _to, uint256 _tokenId) internal whenNotPaused { uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address _from, uint256 _tokenId) internal whenNotPaused { uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal whenNotPaused { super._mint(_to, _tokenId); _addTokenTo(_to,_tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } //override //add Enumerable info function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused { super._transfer(_from, _to, _tokenId); _addTokenTo(_to,_tokenId); _removeTokenFrom(_from, _tokenId); } } contract AvatarToken is ERC998TopDownToken, AvatarService { using UrlStr for string; event BatchMount(address indexed from, uint256 parent, address indexed childAddr, uint256[] children); event BatchUnmount(address indexed from, uint256 parent, address indexed childAddr, uint256[] children); struct Avatar { // avatar name string name; // avatar gen,this decide the avatar appearance uint256 dna; } // For erc721 metadata string internal BASE_URL = "https://www.bitguild.com/bitizens/api/avatar/getAvatar/00000000"; Avatar[] avatars; function createAvatar(address _owner, string _name, uint256 _dna) external onlyOperator returns(uint256) { return _createAvatar(_owner, _name, _dna); } function getMountTokenIds(address _owner, uint256 _tokenId, address _avatarItemAddress) external view onlyOperator existsToken(_tokenId) returns(uint256[]) { require(tokenIdToTokenOwner[_tokenId] == _owner); return childTokens[_tokenId][_avatarItemAddress]; } function updateAvatarInfo(address _owner, uint256 _tokenId, string _name, uint256 _dna) external onlyOperator existsToken(_tokenId){ require(_owner != address(0), "Invalid address"); require(_owner == tokenIdToTokenOwner[_tokenId] || msg.sender == owner); Avatar storage avatar = avatars[allTokensIndex[_tokenId]]; avatar.name = _name; avatar.dna = _dna; } function updateBaseURI(string _url) external onlyOperator { BASE_URL = _url; } function tokenURI(uint256 _tokenId) external view existsToken(_tokenId) returns (string) { return BASE_URL.generateUrl(_tokenId); } function getOwnedTokenIds(address _owner) external view returns(uint256[] _tokenIds) { _tokenIds = ownedTokens[_owner]; } function getAvatarInfo(uint256 _tokenId) external view existsToken(_tokenId) returns(string _name, uint256 _dna) { Avatar storage avatar = avatars[allTokensIndex[_tokenId]]; _name = avatar.name; _dna = avatar.dna; } function batchMount(address _childContract, uint256[] _childTokenIds, uint256 _tokenId) external { uint256 _len = _childTokenIds.length; require(_len > 0, "No token need to mount"); address tokenOwner = _ownerOf(_tokenId); require(tokenOwner == msg.sender); for(uint8 i = 0; i < _len; ++i) { uint256 childTokenId = _childTokenIds[i]; require(ERC721(_childContract).ownerOf(childTokenId) == tokenOwner); _getChild(msg.sender, _tokenId, _childContract, childTokenId); } emit BatchMount(msg.sender, _tokenId, _childContract, _childTokenIds); } function batchUnmount(address _childContract, uint256[] _childTokenIds, uint256 _tokenId) external { uint256 len = _childTokenIds.length; require(len > 0, "No token need to unmount"); address tokenOwner = _ownerOf(_tokenId); require(tokenOwner == msg.sender); for(uint8 i = 0; i < len; ++i) { uint256 childTokenId = _childTokenIds[i]; _transferChild(msg.sender, _childContract, childTokenId); } emit BatchUnmount(msg.sender,_tokenId,_childContract,_childTokenIds); } // create avatar function _createAvatar(address _owner, string _name, uint256 _dna) private returns(uint256 _tokenId) { require(_owner != address(0)); Avatar memory avatar = Avatar(_name, _dna); _tokenId = avatars.push(avatar); _mint(_owner, _tokenId); } function _unmountSameSocketItem(address _owner, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal { uint256[] storage tokens = childTokens[_tokenId][_childContract]; for(uint256 i = 0; i < tokens.length; ++i) { // if the child no compareItemSlots(uint256,uint256) ,this will lead to a error and stop this operate if(AvatarChildService(_childContract).compareItemSlots(tokens[i], _childTokenId)) { // unmount the old avatar item _transferChild(_owner, _childContract, tokens[i]); } } } // override function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused { // not allown to transfer when only one avatar require(tokenOwnerToTokenCount[_from] > 1); super._transfer(_from, _to, _tokenId); } // override function _getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal { _unmountSameSocketItem(_from, _tokenId, _childContract, _childTokenId); super._getChild(_from, _tokenId, _childContract, _childTokenId); } function () external payable { revert(); } }
Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } }
580,721
./full_match/5/0xD718950E7429a3eD40485b776D3d45597f5EB462/sources/contracts/Contract.sol
first count the number of bokemons the user has
function getMetaDataBokemonPerUser(address _user) public view returns (string[] memory) { uint256 count = 0; for (uint i = 0; i < _tokenIds.current(); i++) { if (balanceOf(_user, i) == 1) { count++; } } uint256 index = 0; for (uint i = 0; i < _tokenIds.current(); i++) { if (balanceOf(_user, i) == 1) { bokemons[index] = metadata[i]; index++; } } return bokemons; }
1,878,498
./full_match/10/0x7A2Cf54897345b5f6a9006e2dA19B3739c4f5DCE/sources/contracts/rubiconPools/BathToken.sol
returns the amount of underlying ERC20 tokens in this pool in addition to any tokens that may be outstanding in the Rubicon order book
function underlyingBalance() public view returns (uint256) { require(initialized, "BathToken not initialized"); uint256 _pool = IERC20(underlyingToken).balanceOf(address(this)); return _pool.add(outstandingAmount); }
3,777,969
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) 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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/AURA.sol // OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol) pragma solidity ^0.8.7; /** * @dev Interface for checking active staked balance of a user. */ interface IAURASource { function getAccumulatedHardStakeAmount(address staker) external view returns (uint256); function getAccumulatedPassiveStakeAmount(address _owner) external view returns (uint256); } /** * @dev Implementation of the {IERC20} interface. */ contract AURA is ERC20, ReentrancyGuard, Ownable { IAURASource public AURASource; uint256 public MAX_SUPPLY; uint256 public constant MAX_TAX_VALUE = 100; uint256 public spendTaxAmount; uint256 public withdrawTaxAmount; uint256 public bribesDistributed; uint256 public activeTaxCollectedAmount; bool public tokenCapSet; bool public withdrawTaxCollectionStopped; bool public spendTaxCollectionStopped; bool public isPaused; bool public isDepositPaused; bool public isWithdrawPaused; bool public isTransferPaused; mapping (address => bool) private _isAuthorised; address[] public authorisedLog; mapping(address => uint256) public depositedAmount; mapping(address => uint256) public spentAmount; modifier onlyAuthorised { require(_isAuthorised[_msgSender()], "Not Authorised"); _; } modifier whenNotPaused { require(!isPaused, "Transfers paused!"); _; } event Withdraw(address indexed userAddress, uint256 amount, uint256 tax); event Deposit(address indexed userAddress, uint256 amount); event DepositFor(address indexed caller, address indexed userAddress, uint256 amount); event Spend(address indexed caller, address indexed userAddress, uint256 amount, uint256 tax); event ClaimTax(address indexed caller, address indexed userAddress, uint256 amount); event InternalTransfer(address indexed from, address indexed to, uint256 amount); constructor(address _source) ERC20("$AURA", "AURA") { _isAuthorised[_msgSender()] = true; isPaused = true; isTransferPaused = true; withdrawTaxAmount = 25; spendTaxAmount = 25; AURASource = IAURASource(_source); } /** * @dev Returnes current spendable balance of a specific user. This balance can be spent by user for other collections without * withdrawal to ERC-20 AURA OR can be withdrawn to ERC-20 AURA. */ function getUserBalance(address user) public view returns (uint256) { return (AURASource.getAccumulatedHardStakeAmount(user) + AURASource.getAccumulatedPassiveStakeAmount(user) + depositedAmount[user] - spentAmount[user]); } /** * @dev Function to deposit ERC-20 AURA to the game balance. */ function depositAURA(uint256 amount) public nonReentrant whenNotPaused { require(!isDepositPaused, "Deposit Paused"); require(balanceOf(_msgSender()) >= amount, "Insufficient balance"); _burn(_msgSender(), amount); depositedAmount[_msgSender()] += amount; emit Deposit( _msgSender(), amount ); } /** * @dev Function to withdraw game AURA to ERC-20 AURA. */ function withdrawAURA(uint256 amount) public nonReentrant whenNotPaused { require(!isWithdrawPaused, "Withdraw Paused"); require(getUserBalance(_msgSender()) >= amount, "Insufficient balance"); uint256 tax = withdrawTaxCollectionStopped ? 0 : (amount * withdrawTaxAmount) / 100; spentAmount[_msgSender()] += amount; activeTaxCollectedAmount += tax; _mint(_msgSender(), (amount - tax)); emit Withdraw( _msgSender(), amount, tax ); } /** * @dev Function to transfer game AURA from one account to another. */ function transferAURA(address to, uint256 amount) public nonReentrant whenNotPaused { require(!isTransferPaused, "Transfer Paused"); require(getUserBalance(_msgSender()) >= amount, "Insufficient balance"); spentAmount[_msgSender()] += amount; depositedAmount[to] += amount; emit InternalTransfer( _msgSender(), to, amount ); } /** * @dev Function to spend user balance. Can be called by other authorised contracts. To be used for internal purchases of other NFTs, etc. */ function spendAURA(address user, uint256 amount) external onlyAuthorised nonReentrant { require(getUserBalance(user) >= amount, "Insufficient balance"); uint256 tax = spendTaxCollectionStopped ? 0 : (amount * spendTaxAmount) / 100; spentAmount[user] += amount; activeTaxCollectedAmount += tax; emit Spend( _msgSender(), user, amount, tax ); } /** * @dev Function to deposit tokens to a user balance. Can be only called by an authorised contracts. */ function depositAURAFor(address user, uint256 amount) public onlyAuthorised nonReentrant { _depositAURAFor(user, amount); } /** * @dev Function to tokens to the user balances. Can be only called by an authorised users. */ function distributeAURA(address[] memory user, uint256[] memory amount) public onlyAuthorised nonReentrant { require(user.length == amount.length, "Wrong arrays passed"); for (uint256 i; i < user.length; i++) { _depositAURAFor(user[i], amount[i]); } } function _depositAURAFor(address user, uint256 amount) internal { require(user != address(0), "Deposit to 0 address"); depositedAmount[user] += amount; emit DepositFor( _msgSender(), user, amount ); } /** * @dev Function to mint tokens to a user balance. Can be only called by an authorised contracts. */ function mintFor(address user, uint256 amount) external onlyAuthorised nonReentrant { if (tokenCapSet) require(totalSupply() + amount <= MAX_SUPPLY, "You try to mint more than max supply"); _mint(user, amount); } /** * @dev Function to claim tokens from the tax accumulated pot. Can be only called by an authorised contracts. */ function claimAURATax(address user, uint256 amount) public onlyAuthorised nonReentrant { require(activeTaxCollectedAmount >= amount, "Insufficiend tax balance"); activeTaxCollectedAmount -= amount; depositedAmount[user] += amount; bribesDistributed += amount; emit ClaimTax( _msgSender(), user, amount ); } /** * @dev Function returns maxSupply set by admin. By default returns error (Max supply is not set). */ function getMaxSupply() public view returns (uint256) { require(tokenCapSet, "Max supply is not set"); return MAX_SUPPLY; } /* ADMIN FUNCTIONS */ /** * @dev Function allows admin to set total supply of AURA token. */ function setTokenCap(uint256 tokenCup) public onlyOwner { require(totalSupply() < tokenCup, "Value is smaller than the number of existing tokens"); require(!tokenCapSet, "Token cap has been already set"); MAX_SUPPLY = tokenCup; } /** * @dev Function allows admin add authorised address. The function also logs what addresses were authorised for transparancy. */ function authorise(address addressToAuth) public onlyOwner { _isAuthorised[addressToAuth] = true; authorisedLog.push(addressToAuth); } /** * @dev Function allows admin add unauthorised address. */ function unauthorise(address addressToUnAuth) public onlyOwner { _isAuthorised[addressToUnAuth] = false; } /** * @dev Function allows admin update the address of staking address. */ function changeAURASourceContract(address _source) public onlyOwner { AURASource = IAURASource(_source); authorise(_source); } /** * @dev Function allows admin to update limmit of tax on withdraw. */ function updateWithdrawTaxAmount(uint256 _taxAmount) public onlyOwner { require(_taxAmount < MAX_TAX_VALUE, "Wrong value passed"); withdrawTaxAmount = _taxAmount; } /** * @dev Function allows admin to update tax amount on spend. */ function updateSpendTaxAmount(uint256 _taxAmount) public onlyOwner { require(_taxAmount < MAX_TAX_VALUE, "Wrong value passed"); spendTaxAmount = _taxAmount; } /** * @dev Function allows admin to stop tax collection on withdraw. */ function stopTaxCollectionOnWithdraw(bool _stop) public onlyOwner { withdrawTaxCollectionStopped = _stop; } /** * @dev Function allows admin to stop tax collection on spend. */ function stopTaxCollectionOnSpend(bool _stop) public onlyOwner { spendTaxCollectionStopped = _stop; } /** * @dev Function allows admin to pause all in game AURA transfactions. */ function pauseGameAURA(bool _pause) public onlyOwner { isPaused = _pause; } /** * @dev Function allows admin to pause in game AURA transfers. */ function pauseTransfers(bool _pause) public onlyOwner { isTransferPaused = _pause; } /** * @dev Function allows admin to pause in game AURA withdraw. */ function pauseWithdraw(bool _pause) public onlyOwner { isWithdrawPaused = _pause; } /** * @dev Function allows admin to pause in game AURA deposit. */ function pauseDeposits(bool _pause) public onlyOwner { isDepositPaused = _pause; } /** * @dev Function allows admin to withdraw ETH accidentally dropped to the contract. */ function rescue() external onlyOwner { payable(owner()).transfer(address(this).balance); } }
Function allows admin to pause all in game AURA transfactions./
function pauseGameAURA(bool _pause) public onlyOwner { isPaused = _pause; }
12,192,168
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract Profiles { struct Profile { address addr; string firstName; string location; uint256 birthdayYear; string gender; string orientation; string bio; } address[] public datingAccounts; mapping(address => Profile) public profiles; mapping(address => address[]) public matches; constructor() public {} function createProfile( string memory firstName, string memory location, uint256 birthdayYear, string memory gender, string memory orientation, string memory bio ) public { Profile memory account = Profile( msg.sender, firstName, location, birthdayYear, gender, orientation, bio ); profiles[msg.sender] = account; datingAccounts.push(account.addr); } function makeMatches( address addr, uint256 age, string memory gender, string memory orientation ) public { for (uint256 i = 0; i < datingAccounts.length; i++) { if ( getAge(datingAccounts[i]) == age && compareStrings(getGender(datingAccounts[i]), gender) && compareStrings(getOrientation(datingAccounts[i]), orientation) ) { matches[addr].push(datingAccounts[i]); } } } // returns the address array of matches that has been mapped to the given address function getMatches(address addr) public view returns (address[] memory) { return matches[addr]; } // gets all accounts/addresses on the network function getAccounts() public view returns (address[] memory) { return datingAccounts; } // gets all stored information of given account/address function getAccount(address acct) public view returns ( string memory, string memory, uint256, string memory, string memory, string memory ) { return ( profiles[acct].firstName, profiles[acct].location, profiles[acct].birthdayYear, profiles[acct].gender, profiles[acct].orientation, profiles[acct].bio ); } // getter functions using address function getName(address addr) public view returns (string memory) { return profiles[addr].firstName; } function getLocation(address addr) public view returns (string memory) { return profiles[addr].location; } function getAge(address addr) public view returns (uint256) { uint256 age = (2021 - profiles[addr].birthdayYear); return age; } function getGender(address addr) public view returns (string memory) { return profiles[addr].gender; } function getOrientation(address addr) public view returns (string memory) { return profiles[addr].orientation; } // getter functions using index function getNameIndex(uint256 index) public view returns (string memory) { return profiles[datingAccounts[index]].firstName; } function getLocationIndex(uint256 index) public view returns (string memory) { return profiles[datingAccounts[index]].location; } function getAgeIndex(uint256 index) public view returns (uint256) { uint256 age = (2021 - profiles[datingAccounts[index]].birthdayYear); return age; } function getGenderIndex(uint256 index) public view returns (string memory) { return profiles[datingAccounts[index]].gender; } function getOrientationIndex(uint256 index) public view returns (string memory) { return profiles[datingAccounts[index]].orientation; } // simple functions to do with comparing variables function compareStrings(string memory a, string memory b) public pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } }
gets all accounts/addresses on the network
function getAccounts() public view returns (address[] memory) { return datingAccounts; }
12,738,628
pragma solidity >=0.5.0; //Interfaces import './interfaces/IAddressResolver.sol'; import './interfaces/ISettings.sol'; import './interfaces/IERC20.sol'; import './interfaces/IBaseUbeswapAdapter.sol'; import "./interfaces/IStableCoinStakingRewards.sol"; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IStakingRewards.sol'; import './interfaces/IPool.sol'; //Inheritance import './interfaces/ILeveragedLiquidityPositionManager.sol'; import './LeveragedFarmingRewards.sol'; //Libraries import './libraries/SafeMath.sol'; contract LeveragedLiquidityPositionManager is ILeveragedLiquidityPositionManager, LeveragedFarmingRewards { using SafeMath for uint; uint public numberOfLeveragedPositions; mapping (address => uint[]) public userPositions; mapping (uint => LeveragedLiquidityPosition) public leveragedPositions; mapping (address => mapping (address => uint)) public positionIndexes; //maps to (index + 1), with index 0 representing position not found constructor(IAddressResolver addressResolver) public LeveragedFarmingRewards(addressResolver) { } /* ========== VIEWS ========== */ /** * @dev Returns the index of each leveraged position the user has * @param user Address of the user * @return uint[] Index of each position */ function getUserPositions(address user) public view override returns (uint[] memory) { require(user != address(0), "LeveragedLiquidityPositionManager: invalid user address"); return userPositions[user]; } /** * @dev Given the index of a leveraged position, return the position info * @param positionIndex Index of the leveraged position in array of leveraged positions * @return (address, address, address, uint, uint, uint, uint) Leveraged position's owner, address of liquidity pair, address of liquidity pair's Ubeswap farm, entry timestamp, number of tokens collateral, number of tokens borrowed, and entry price */ function getPositionInfo(uint positionIndex) public view override positionIndexInRange(positionIndex) returns (address, address, address, uint, uint, uint, uint) { LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; return (position.owner, position.pair, position.farm, position.entryTimestamp, position.collateral, position.numberOfTokensBorrowed, position.entryPrice); } /** * @dev Given the index of a leveraged position, returns the position value in USD * @param positionIndex Index of the leveraged position in array of leveraged positions * @return uint Value of the position in USD */ function getPositionValue(uint positionIndex) public view override positionIndexInRange(positionIndex) returns (uint) { address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; uint interestAccrued = calculateInterestAccrued(positionIndex); address token0 = IUniswapV2Pair(position.pair).token0(); address token1 = IUniswapV2Pair(position.pair).token1(); (uint amount0, uint amount1) = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getTokenAmountsFromPair(token0, token1, position.collateral.add(position.numberOfTokensBorrowed)); //Get price of token0 uint numberOfDecimals0 = IERC20(token0).decimals(); uint USDperToken0 = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(token0); uint USDBalance0 = amount0.mul(USDperToken0).div(10 ** numberOfDecimals0); //Get price of token1 uint numberOfDecimals1 = IERC20(token1).decimals(); uint USDperToken1 = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(token1); uint USDBalance1 = amount1.mul(USDperToken1).div(10 ** numberOfDecimals1); //Calculate current price of LP token uint priceOfLPToken = (USDBalance0.add(USDBalance1)).div(position.collateral.add(position.numberOfTokensBorrowed)); uint collateralValue = (position.collateral.add(position.numberOfTokensBorrowed)).mul(priceOfLPToken).div(10 ** 18); uint loanValue = (priceOfLPToken > position.entryPrice) ? (priceOfLPToken.sub(position.entryPrice)).mul(position.numberOfTokensBorrowed).div(10 ** 18) : (position.entryPrice.sub(priceOfLPToken)).mul(position.numberOfTokensBorrowed).div(10 ** 18); return (priceOfLPToken > position.entryPrice) ? collateralValue.add(loanValue).sub(interestAccrued) : collateralValue.sub(loanValue).sub(interestAccrued); } /** * @dev Given the index of a position, returns whether the position can be liquidated * @param positionIndex Index of the leveraged position in array of leveraged positions * @return bool Whether the position can be liquidated */ function checkIfPositionCanBeLiquidated(uint positionIndex) public view override positionIndexInRange(positionIndex) returns (bool) { return (_getPriceOfLPToken(positionIndex) < calculateLiquidationPrice(positionIndex)); } /** * @dev Given the index of a position, returns the position's leverage factor; (number of tokens borrowed + interest accrued) / collateral * @param positionIndex Index of the leveraged position in array of leveraged positions * @return uint Leverage factor */ function calculateLeverageFactor(uint positionIndex) public view override positionIndexInRange(positionIndex) returns (uint) { uint interestAccrued = calculateInterestAccrued(positionIndex); return (leveragedPositions[positionIndex].numberOfTokensBorrowed.add(interestAccrued)).div(leveragedPositions[positionIndex].collateral); } /** * @dev Calculates the amount of interest accrued (in LP tokens) on a leveraged position * @param positionIndex Index of the leveraged position in array of leveraged positions * @return uint Amount of interest accrued in asset tokens */ function calculateInterestAccrued(uint positionIndex) public view override positionIndexInRange(positionIndex) returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); uint interestRate = ISettings(settingsAddress).getParameterValue("InterestRateOnLeveragedLiquidityPositions"); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; return position.numberOfTokensBorrowed.mul(block.timestamp.sub(position.entryTimestamp)).mul(interestRate).div(365 days); } /** * @dev Calculates the price at which a position can be liquidated * @param positionIndex Index of the leveraged position in array of leveraged positions * @return uint Liquidation price */ function calculateLiquidationPrice(uint positionIndex) public view override positionIndexInRange(positionIndex) returns (uint) { LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; uint leverageFactor = calculateLeverageFactor(positionIndex); uint numerator = position.entryPrice.mul(8); uint denominator = leverageFactor.mul(10); return position.entryPrice.sub(numerator.div(denominator)); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Opens a new leveraged position; swaps cUSD for specified asset * @notice User needs to approve cUSD for StableCoinStakingRewards contract before calling this function * @param tokenA Address of first token in pair * @param tokenB Address of second token in pair * @param collateral Amount of cUSD to use as collateral * @param amountToBorrow Amount of cUSD to borrow * @param farmAddress Address of token pair's Ubeswap farm */ function openPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) public override { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); require(tokenA != address(0), "LeveragedLiquidityPositionManager: invalid address for tokenA"); require(tokenB != address(0), "LeveragedLiquidityPositionManager: invalid address for tokenB"); require(collateral > 0, "LeveragedLiquidityPositionManager: collateral must be greater than 0"); require(amountToBorrow > 0, "LeveragedLiquidityPositionManager: amount to borrow must be greater than 0"); require(amountToBorrow <= collateral.mul(9), "LeveragedLiquidityPositionManager: leverage cannot be higher than 10x"); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(tokenA), "LeveragedLiquidityPositionManager: tokenA not available"); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(tokenB), "LeveragedLiquidityPositionManager: tokenB not available"); require(userPositions[msg.sender].length < ISettings(settingsAddress).getParameterValue("MaximumNumberOfLeveragedPositions"), "LeveragedLiquidityPositionManager: cannot exceed maximum number of leveraged positions"); //Check if user has existing leveraged position with this pair address pair = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB); //Add to position if (positionIndexes[msg.sender][pair] > 0) { _combinePositions(positionIndexes[msg.sender][pair].sub(1), collateral, amountToBorrow); } //Open a new position else { _openPosition(tokenA, tokenB, collateral, amountToBorrow, farmAddress); positionIndexes[msg.sender][pair] = numberOfLeveragedPositions; } } /** * @dev Reduces the size of a leveraged position * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of tokens to sell */ function reducePosition(uint positionIndex, uint numberOfTokens) public override positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { require(numberOfTokens > 0, "LeveragedLiquidityPositionManager: number of tokens must be greater than 0"); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; //Pay interest uint interestPaid = _payInterest(positionIndex); //Update state variables in rewards contract and claim available UBE getReward(positionIndex); _unstake(msg.sender, position.farm, numberOfTokens); require(numberOfTokens < position.collateral.add(position.numberOfTokensBorrowed), "LeveragedLiquidityPositionManager: number of tokens must be less than position size"); //Calculate user and pool cUSD share uint userShare = _calculateUserUSDShare(positionIndex, numberOfTokens); uint poolShare = getPositionValue(positionIndex).sub(userShare).mul(numberOfTokens).div(position.collateral.add(position.numberOfTokensBorrowed)); //Maintain leverage factor uint collateralToRemove = numberOfTokens.mul(position.collateral).div(position.collateral.add(position.numberOfTokensBorrowed)); uint numberOfBorrowedTokensToRemove = numberOfTokens.mul(position.numberOfTokensBorrowed).div(position.collateral.add(position.numberOfTokensBorrowed)); //Update state variables leveragedPositions[positionIndex].collateral = position.collateral.sub(collateralToRemove); leveragedPositions[positionIndex].numberOfTokensBorrowed = position.numberOfTokensBorrowed.sub(numberOfBorrowedTokensToRemove); //Remove liquidity address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); (uint amount0, uint amount1) = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).removeLiquidity(position.pair, position.farm, numberOfTokens); //Swap from token0 to cUSD uint cUSDReceived0 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapFromAsset(IUniswapV2Pair(position.pair).token0(), userShare, poolShare, amount0, msg.sender); //Swap from token1 to cUSD uint cUSDReceived1 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapFromAsset(IUniswapV2Pair(position.pair).token1(), userShare, poolShare, amount1, msg.sender); emit ReducedPosition(msg.sender, positionIndex, cUSDReceived0.add(cUSDReceived1), interestPaid, block.timestamp); } /** * @dev Closes a leveraged position * @param positionIndex Index of the leveraged position in array of leveraged positions */ function closePosition(uint positionIndex) public override positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { //Pay interest uint interestAccrued = _payInterest(positionIndex); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; //Update state variables in rewards contract and claim available UBE _unstake(msg.sender, position.farm, position.collateral.add(position.numberOfTokensBorrowed).add(interestAccrued)); getReward(positionIndex); //Get updated position size uint positionSize = position.collateral.add(position.numberOfTokensBorrowed); //Calculate user and pool cUSD share uint userShare = _calculateUserUSDShare(positionIndex, positionSize); uint poolShare = getPositionValue(positionIndex).sub(userShare); //Update state variables _removePosition(positionIndex); //Remove liquidity address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); (uint amount0, uint amount1) = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).removeLiquidity(position.pair, position.farm, positionSize); //Swap from token0 to cUSD uint cUSDReceived0 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapFromAsset(IUniswapV2Pair(position.pair).token0(), userShare, poolShare, amount0, msg.sender); //Swap from token1 to cUSD uint cUSDReceived1 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapFromAsset(IUniswapV2Pair(position.pair).token1(), userShare, poolShare, amount1, msg.sender); emit ClosedPosition(msg.sender, positionIndex, interestAccrued, cUSDReceived0.add(cUSDReceived1), block.timestamp); } /** * @dev Adds collateral to the leveraged position * @notice User needs to approve cUSD for StableCoinStakingRewards contract before calling this function * @param positionIndex Index of the leveraged position in array of leveraged positions * @param amountOfUSD Amount of cUSD to add as collateral */ function addCollateral(uint positionIndex, uint amountOfUSD) public override positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { require(amountOfUSD > 0, "LeveragedAssetPositionManager: amount of USD must be greater than 0"); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address pair = position.pair; //Swap cUSD for token0 uint numberOfTokensReceived0 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapToAsset(IUniswapV2Pair(pair).token0(), amountOfUSD.div(2), 0, msg.sender); //Swap cUSD for token1 uint numberOfTokensReceived1 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapToAsset(IUniswapV2Pair(pair).token1(), amountOfUSD.div(2), 0, msg.sender); //Get current price of token0 uint USDperToken0 = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(IUniswapV2Pair(pair).token0()); //Get current price of token1 uint USDperToken1 = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(IUniswapV2Pair(pair).token1()); //Add liquidity uint numberOfLPTokens = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).addLiquidity(IUniswapV2Pair(pair).token0(), IUniswapV2Pair(pair).token1(), numberOfTokensReceived0, numberOfTokensReceived1, position.farm); //Claim available UBE and update state variables in rewards contract getReward(positionIndex); _stake(msg.sender, position.farm, numberOfLPTokens); //Calculate new entry price uint initialPositionValue = position.entryPrice.mul(position.collateral.add(position.numberOfTokensBorrowed)); uint addedAmount = (USDperToken0.mul(numberOfTokensReceived0)).add(USDperToken1.mul(numberOfTokensReceived1)); uint newEntryPrice = (initialPositionValue.add(addedAmount)).div(numberOfLPTokens.add(position.collateral).add(position.numberOfTokensBorrowed)); //Update state variables leveragedPositions[positionIndex].collateral = position.collateral.add(numberOfLPTokens); leveragedPositions[positionIndex].entryPrice = newEntryPrice; emit AddedCollateral(msg.sender, positionIndex, numberOfLPTokens, block.timestamp); } /** * @dev Removes collateral from the leveraged position * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of asset tokens to remove as collateral */ function removeCollateral(uint positionIndex, uint numberOfTokens) public override positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { require(numberOfTokens > 0, "LeveragedLiquidityPositionManager: number of tokens must be greater than 0"); require(numberOfTokens < leveragedPositions[positionIndex].collateral, "LeveragedLiquidityPositionManager: number of tokens must be less than collateral"); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; //Claim available UBE and update state variables in rewards contract getReward(positionIndex); _unstake(msg.sender, position.farm, numberOfTokens); leveragedPositions[positionIndex].collateral = position.collateral.sub(numberOfTokens); require(calculateLeverageFactor(positionIndex) <= 10, "LeveragedLiquidityPositionManager: cannot exceed 10x leverage"); //Remove liquidity address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); (uint amount0, uint amount1) = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).removeLiquidity(position.pair, position.farm, numberOfTokens); //Swap from token0 to cUSD uint cUSDReceived0 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapFromAsset(IUniswapV2Pair(position.pair).token0(), 100, 0, amount0, msg.sender); //Swap from token1 to cUSD uint cUSDReceived1 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapFromAsset(IUniswapV2Pair(position.pair).token1(), 100, 0, amount1, msg.sender); emit RemovedCollateral(msg.sender, positionIndex, numberOfTokens, cUSDReceived0.add(cUSDReceived1), block.timestamp); } /** * @dev Transfers leveraged position to another contract * @param positionIndex Index of the leveraged position in array of leveraged positions * @param newOwner Address of contract to transfer ownership to */ function transferOwnership(uint positionIndex, address newOwner) public override positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { require(newOwner != address(0), "LeveragedLiquidityPositionManager: invalid address for new owner"); require(newOwner != msg.sender, "LeveragedLiquidityPositionManager: new owner is same as current owner"); //Update state variable in rewards contract and send available UBE to user _transferOwnership(newOwner, positionIndex); //Check if new owner can add a new leveraged position address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); require(userPositions[newOwner].length < ISettings(settingsAddress).getParameterValue("MaximumNumberOfLeveragedPositions"), "LeveragedLiquidityPositionManager: new owner has too many leveraged positions"); //Update owner of leveraged position leveragedPositions[positionIndex].owner = newOwner; //Get index of leveraged position in old owner's position array uint indexInOldOwnerArray = leveragedPositions[positionIndex].indexInOwnerPositionArray; //Remove position from old owner's array of leveraged positions userPositions[msg.sender][indexInOldOwnerArray] = userPositions[msg.sender][userPositions[msg.sender].length - 1]; userPositions[msg.sender].pop(); //Update index of position in old owner position array leveragedPositions[userPositions[msg.sender][indexInOldOwnerArray]].indexInOwnerPositionArray = indexInOldOwnerArray; //Add position to new owner's array of leveraged positions userPositions[newOwner].push(positionIndex); //Update index of position in new owner position array leveragedPositions[positionIndex].indexInOwnerPositionArray = userPositions[newOwner].length.sub(1); emit TransferredOwnership(msg.sender, newOwner, positionIndex, block.timestamp); } /** * @dev Claims available UBE rewards for the farm * @notice Sends a small percentage of claimed UBE to the function's caller as a reward for maintaining the protocol * @param farmAddress Address of the farm */ function claimFarmUBE(address farmAddress) public override { address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); require (IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "LeveragedLiquidityPositionManager: invalid farm address"); (uint claimedUBE, uint keeperShare) = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).claimFarmUBE(msg.sender, farmAddress); _updateAvailableUBE(farmAddress, claimedUBE); emit ClaimedFarmUBE(msg.sender, farmAddress, claimedUBE, keeperShare, block.timestamp); } /** * @dev Liquidates part of the leveraged position * @param positionIndex Index of the leveraged position in array of leveraged positions */ function liquidate(uint positionIndex) public override { require(checkIfPositionCanBeLiquidated(positionIndex), "LeveragedLiquidityPositionManager: current price is above liquidation price"); //Pay interest _payInterest(positionIndex); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; address owner = leveragedPositions[positionIndex].owner; //Get updated position size uint positionSize = position.collateral.add(position.numberOfTokensBorrowed); //Get liquidation fee address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); uint liquidationFee = ISettings(settingsAddress).getParameterValue("LiquidationFee"); //Calculate user and pool cUSD share uint userShare = _calculateUserUSDShare(positionIndex, positionSize); uint liquidatorShare = userShare.mul(liquidationFee).div(100); uint poolShare = getPositionValue(positionIndex).sub(userShare).sub(liquidatorShare); //Remove liquidity address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); (uint amount0, uint amount1) = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).removeLiquidity(position.pair, position.farm, positionSize); //Swap from token0 to cUSD uint cUSDReceived0 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).liquidateLeveragedAsset(IUniswapV2Pair(position.pair).token0(), userShare, liquidatorShare, poolShare, amount0, owner, msg.sender); //Swap from token1 to cUSD uint cUSDReceived1 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).liquidateLeveragedAsset(IUniswapV2Pair(position.pair).token1(), userShare, liquidatorShare, poolShare, amount1, owner, msg.sender); //Update state variables in rewards contract _unstake(position.owner, position.farm, positionSize); //Claim available UBE getReward(positionIndex); _removePosition(positionIndex); _decrementPositionCountIfAddressIsPool(owner); emit Liquidated(owner, msg.sender, positionIndex, cUSDReceived0.add(cUSDReceived1), liquidatorShare, block.timestamp); } /** * @dev Claims available UBE rewards for the position * @param positionIndex Index of the leveraged position in array of leveraged positions */ function getReward(uint positionIndex) public override positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { //Claim available UBE for farm claimFarmUBE(leveragedPositions[positionIndex].farm); uint reward = _getReward(leveragedPositions[positionIndex].farm); _updateAvailableUBE(leveragedPositions[positionIndex].farm, reward); //Claim user's share of available UBE address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); IStableCoinStakingRewards(stableCoinStakingRewardsAddress).claimUserUBE(msg.sender, reward); emit RewardPaid(msg.sender, reward, leveragedPositions[positionIndex].farm, block.timestamp); } /** * @dev Transfers part of each position the caller has to the recipient; meant to be called from a Pool * @param recipient Address of user receiving the tokens * @param numerator Numerator used for calculating ratio of tokens * @param denominator Denominator used for calculating ratio of tokens */ function bulkTransferTokens(address recipient, uint numerator, uint denominator) public override onlyPool { require(recipient != address(0), "LeveragedLiquidityPositionManager: invalid recipient address"); require(numerator > 0, "LeveragedLiquidityPositionManager: numerator must be greater than 0"); require(denominator > 0, "LeveragedLiquidityPositionManager: denominator must be greater than 0"); for (uint i = 0; i < userPositions[msg.sender].length; i++) { _transferTokens(userPositions[msg.sender][i], recipient, numerator, denominator); } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Removes the given position from user's position array and updates state variables accordingly * @param positionIndex Index of the leveraged position in array of leveraged positions */ function _removePosition(uint positionIndex) internal positionIndexInRange(positionIndex) { uint indexInUserPositionArray = leveragedPositions[positionIndex].indexInOwnerPositionArray; address lastUser = leveragedPositions[numberOfLeveragedPositions - 1].owner; uint indexInLastUserPositionArray = leveragedPositions[numberOfLeveragedPositions - 1].indexInOwnerPositionArray; delete positionIndexes[msg.sender][leveragedPositions[positionIndex].pair]; //Swap with last element in user position array and remove last element userPositions[msg.sender][indexInUserPositionArray] = userPositions[msg.sender][userPositions[msg.sender].length]; userPositions[msg.sender].pop(); //Update index of swapped element in main position array leveragedPositions[userPositions[msg.sender][indexInUserPositionArray]].indexInOwnerPositionArray = indexInUserPositionArray; //Swap with last element in main position array and remove last element leveragedPositions[positionIndex] = leveragedPositions[numberOfLeveragedPositions - 1]; //Update index in last user position array userPositions[lastUser][indexInLastUserPositionArray] = positionIndex; } /** * @dev Given the index of a position, calculates and pays the accrued interest * @param positionIndex Index of the leveraged position in array of leveraged positions * @return uint Amount of interest paid */ function _payInterest(uint positionIndex) internal positionIndexInRange(positionIndex) returns (uint) { uint interestAccrued = calculateInterestAccrued(positionIndex); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; //Remove interest accrued from LP token balance in rewards contract _unstake(position.owner, position.farm, interestAccrued); //Remove collateral and borrowed tokens to maintain leverage factor leveragedPositions[positionIndex].collateral = position.collateral.sub(interestAccrued); leveragedPositions[positionIndex].numberOfTokensBorrowed = position.numberOfTokensBorrowed.sub(interestAccrued.mul(calculateLeverageFactor(positionIndex))); leveragedPositions[positionIndex].entryTimestamp = block.timestamp; //Pay interest //Split payment evenly between the two tokens address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); if (interestAccrued > 0) { IStableCoinStakingRewards(stableCoinStakingRewardsAddress).payInterest(IUniswapV2Pair(position.pair).token0(), interestAccrued.div(2)); IStableCoinStakingRewards(stableCoinStakingRewardsAddress).payInterest(IUniswapV2Pair(position.pair).token1(), interestAccrued.div(2)); } return interestAccrued; } /** * @dev Given the index of a position, returns the amount of USD received for the given number of LP tokens * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of LP tokens in the position's liquidity pair * @return uint Amount of USD received */ function _calculateUserUSDShare(uint positionIndex, uint numberOfTokens) internal view positionIndexInRange(positionIndex) returns (uint) { require(numberOfTokens > 0, "LeveragedLiquidityPositionManager: number of tokens must be greater than 0"); require(numberOfTokens <= leveragedPositions[positionIndex].collateral.add(leveragedPositions[positionIndex].numberOfTokensBorrowed), "LeveragedLiquidityPositionManager: number of tokens must be less than position size"); LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; uint collateralInUSD = position.entryPrice.mul(position.collateral); uint USDperToken = _getPriceOfLPToken(positionIndex); uint delta = (USDperToken > position.entryPrice) ? (USDperToken.sub(position.entryPrice)).mul(position.collateral.add(position.numberOfTokensBorrowed)) : (position.entryPrice.sub(USDperToken)).mul(position.collateral.add(position.numberOfTokensBorrowed)); return (USDperToken > position.entryPrice) ? (collateralInUSD.add(delta)).mul(numberOfTokens).div(position.collateral.add(position.numberOfTokensBorrowed)) : (collateralInUSD.sub(delta)).mul(numberOfTokens).div(position.collateral.add(position.numberOfTokensBorrowed)); } /** * @dev Given the index of a position, returns the price of the position's pair's LP tokens * @param positionIndex Index of the leveraged position in array of leveraged positions * @return uint Price of LP token */ function _getPriceOfLPToken(uint positionIndex) internal view positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) returns (uint) { uint positionValue = getPositionValue(positionIndex); uint positionSize = leveragedPositions[positionIndex].collateral.add(leveragedPositions[positionIndex].numberOfTokensBorrowed); return positionValue.div(positionSize); } /** * @dev Adds collateral and loan to existing position, and recalculates entry price * @param positionIndex Index of the leveraged position in array of leveraged positions * @param collateral Amount of cUSD to use as collateral * @param amountToBorrow Amount of cUSD to borrow */ function _combinePositions(uint positionIndex, uint collateral, uint amountToBorrow) internal positionIndexInRange(positionIndex) onlyPositionOwner(positionIndex) { LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address pair = position.pair; _payInterest(positionIndex); //Swap cUSD for token0 uint numberOfTokensReceived0 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapToAsset(IUniswapV2Pair(pair).token0(), (collateral.add(amountToBorrow)).div(2), 0, msg.sender); //Swap cUSD for token1 uint numberOfTokensReceived1 = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapToAsset(IUniswapV2Pair(pair).token1(), (collateral.add(amountToBorrow)).div(2), 0, msg.sender); //Add liquidity uint numberOfLPTokens = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).addLiquidity(IUniswapV2Pair(pair).token0(), IUniswapV2Pair(pair).token1(), numberOfTokensReceived0, numberOfTokensReceived1, position.farm); //Calculate new entry price uint initialPositionValue = position.entryPrice.mul(position.collateral.add(position.numberOfTokensBorrowed)); uint addedAmount = collateral.add(amountToBorrow); uint newEntryPrice = (initialPositionValue.add(addedAmount)).div(numberOfLPTokens.add(position.collateral).add(position.numberOfTokensBorrowed)); //Update state variables leveragedPositions[positionIndex].collateral = position.collateral.add(numberOfLPTokens.mul(collateral).div(addedAmount)); leveragedPositions[positionIndex].numberOfTokensBorrowed = position.numberOfTokensBorrowed.add(numberOfLPTokens.mul(amountToBorrow).div(addedAmount)); leveragedPositions[positionIndex].entryPrice = newEntryPrice; //Update state variables in rewards contract _stake(msg.sender, position.farm, numberOfLPTokens); emit CombinedPosition(msg.sender, positionIndex, collateral, amountToBorrow, block.timestamp); } /** * @dev Opens a new leveraged position; swaps cUSD for specified asset * @param tokenA Address of first token in pair * @param tokenB Address of second token in pair * @param collateral Amount of cUSD to use as collateral * @param amountToBorrow Amount of cUSD to borrow * @param farmAddress Address of token pair's Ubeswap farm */ function _openPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) internal { address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); //Check if farm exists for the token pair address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress); address pairAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB); require(stakingTokenAddress == pairAddress, "Pool: stakingTokenAddress does not match pairAddress"); //Swap cUSD for tokenA uint amountA = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapToAsset(tokenA, collateral.div(2), amountToBorrow.div(2), msg.sender); //Swap cUSD for tokenB uint amountB = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).swapToAsset(tokenB, collateral.div(2), amountToBorrow.div(2), msg.sender); //Add liquidity uint numberOfLPTokens = IStableCoinStakingRewards(stableCoinStakingRewardsAddress).addLiquidity(tokenA, tokenB, amountA, amountB, farmAddress); //Adjust collateral and amountToBorrow to asset tokens uint adjustedCollateral = numberOfLPTokens.mul(collateral).div(collateral.add(amountToBorrow)); uint adjustedAmountToBorrow = numberOfLPTokens.mul(amountToBorrow).div(collateral.add(amountToBorrow)); //Get entry price; used for calculating liquidation price uint USDperToken = (collateral.add(amountToBorrow)).div(numberOfLPTokens); leveragedPositions[numberOfLeveragedPositions] = LeveragedLiquidityPosition(msg.sender, pairAddress, farmAddress, block.timestamp, adjustedCollateral, adjustedAmountToBorrow, USDperToken, userPositions[msg.sender].length); userPositions[msg.sender].push(numberOfLeveragedPositions); numberOfLeveragedPositions = numberOfLeveragedPositions.add(1); //Update state variables in rewards contract _stake(msg.sender, farmAddress, numberOfLPTokens); emit OpenedPosition(msg.sender, pairAddress, adjustedCollateral, adjustedAmountToBorrow, USDperToken, numberOfLeveragedPositions.sub(1), block.timestamp); } /** * @dev Updates state variables in rewards contract and sends old owner their share of UBE rewards * @param newOwner New owner of the position * @param positionIndex Index of the leveraged position in array of leveraged positions */ function _transferOwnership(address newOwner, uint positionIndex) internal { LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; _unstake(msg.sender, position.farm, position.collateral.add(position.numberOfTokensBorrowed)); getReward(positionIndex); _stake(newOwner, position.farm, position.collateral.add(position.numberOfTokensBorrowed)); } /** * @dev Decrements the pool's total position count if the supplied address is a valid pool address */ function _decrementPositionCountIfAddressIsPool(address addressToCheck) internal { if (ADDRESS_RESOLVER.checkIfPoolAddressIsValid(addressToCheck)) { IPool(addressToCheck).decrementTotalPositionCount(); } } /** * @dev Transfers part of a position to another user; meant to be called from a Pool * @param positionIndex Index of the leveraged position in array of leveraged positions * @param recipient Address of user receiving the tokens * @param numerator Numerator used for calculating ratio of tokens * @param denominator Denominator used for calculating ratio of tokens */ function _transferTokens(uint positionIndex, address recipient, uint numerator, uint denominator) internal positionIndexInRange(positionIndex) { LeveragedLiquidityPosition memory position = leveragedPositions[positionIndex]; uint numberOfTokens = (position.collateral.add(position.numberOfTokensBorrowed)).mul(numerator).div(denominator); if (numberOfTokens == position.collateral.add(position.numberOfTokensBorrowed)) { transferOwnership(positionIndex, recipient); } else { //Check if recipient can add a new leveraged position address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); require(userPositions[recipient].length < ISettings(settingsAddress).getParameterValue("MaximumNumberOfLeveragedPositions"), "LeveragedLiquidityPositionManager: recipient has too many leveraged positions"); _unstake(msg.sender, position.farm, numberOfTokens); _stake(recipient, position.farm, numberOfTokens); //Combine positions if recipient already has a position in this farm uint recipientPositionIndex = positionIndexes[recipient][position.pair]; //Combine positions if (recipientPositionIndex > 0) { LeveragedLiquidityPosition memory recipientPosition = leveragedPositions[recipientPositionIndex.sub(1)]; //Update state variables leveragedPositions[recipientPositionIndex.sub(1)].collateral = recipientPosition.collateral.add(numberOfTokens.mul(recipientPosition.collateral).div(recipientPosition.collateral.add(recipientPosition.numberOfTokensBorrowed))); leveragedPositions[recipientPositionIndex.sub(1)].numberOfTokensBorrowed = recipientPosition.numberOfTokensBorrowed.add(numberOfTokens.mul(recipientPosition.collateral).div(recipientPosition.collateral.add(recipientPosition.numberOfTokensBorrowed))); } //Open a new position else { uint collateral = numberOfTokens.div(calculateLeverageFactor(positionIndex)); leveragedPositions[numberOfLeveragedPositions] = LeveragedLiquidityPosition(msg.sender, position.pair, position.farm, block.timestamp, collateral, numberOfTokens.sub(collateral), position.entryPrice, userPositions[msg.sender].length); userPositions[recipient].push(numberOfLeveragedPositions); numberOfLeveragedPositions = numberOfLeveragedPositions.add(1); positionIndexes[recipient][position.pair] = numberOfLeveragedPositions; } } } /* ========== MODIFIERS ========== */ modifier onlyPool() { require(ADDRESS_RESOLVER.checkIfPoolAddressIsValid(msg.sender), "LeveragedLiquidityPositionManager: only a Pool can call this function"); _; } modifier onlyPositionOwner(uint positionIndex) { require(leveragedPositions[positionIndex].owner == msg.sender, "LeveragedLiquidityPositionManager: only position owner can call this function"); _; } modifier positionIndexInRange(uint positionIndex) { require(positionIndex > 0, "LeveragedLiquidityPositionManager: position index must be greater than 0"); require(positionIndex < numberOfLeveragedPositions, "LeveragedLiquidityPositionManager: position index out of range"); _; } modifier validFarmAddress(uint positionIndex, address farmAddress) { address pair = leveragedPositions[positionIndex].pair; address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); require(farmAddress != address(0), "LeveragedLiquidityPositionManager: invalid farm address"); require(pair == IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress), "LeveragedLiquidityPositionManager: farm staking token does not match pair address"); _; } /* ========== EVENTS ========== */ event OpenedPosition(address indexed owner, address indexed underlyingAsset, uint collateral, uint numberOfTokensBorrowed, uint entryPrice, uint positionIndex, uint timestamp); event ReducedPosition(address indexed owner, uint indexed positionIndex, uint cUSDReceived, uint interestPaid, uint timestamp); event ClosedPosition(address indexed owner, uint indexed positionIndex, uint interestAccrued, uint cUSDReceived, uint timestamp); event CombinedPosition(address indexed owner, uint indexed positionIndex, uint collateral, uint numberOfTokensBorrowed, uint timestamp); event AddedCollateral(address indexed owner, uint indexed positionIndex, uint collateralAdded, uint timestamp); event RemovedCollateral(address indexed owner, uint indexed positionIndex, uint collateralRemoved, uint cUSDReceived, uint timestamp); event TransferredOwnership(address indexed oldOwner, address newOwner, uint indexed positionIndex, uint timestamp); event Liquidated(address indexed owner, address indexed liquidator, uint indexed positionIndex, uint collateralReturned, uint liquidatorShare, uint timestamp); event ClaimedFarmUBE(address indexed user, address indexed farm, uint claimedUBE, uint keeperShare, uint timestamp); event RewardPaid(address indexed user, uint amount, address farmAddress, uint timestamp); }
Opens a new leveraged position; swaps cUSD for specified asset User needs to approve cUSD for StableCoinStakingRewards contract before calling this function tokenA Address of first token in pair tokenB Address of second token in pair collateral Amount of cUSD to use as collateral amountToBorrow Amount of cUSD to borrow farmAddress Address of token pair's Ubeswap farm/Check if user has existing leveraged position with this pairAdd to position
function openPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) public override { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); require(tokenA != address(0), "LeveragedLiquidityPositionManager: invalid address for tokenA"); require(tokenB != address(0), "LeveragedLiquidityPositionManager: invalid address for tokenB"); require(collateral > 0, "LeveragedLiquidityPositionManager: collateral must be greater than 0"); require(amountToBorrow > 0, "LeveragedLiquidityPositionManager: amount to borrow must be greater than 0"); require(amountToBorrow <= collateral.mul(9), "LeveragedLiquidityPositionManager: leverage cannot be higher than 10x"); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(tokenA), "LeveragedLiquidityPositionManager: tokenA not available"); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(tokenB), "LeveragedLiquidityPositionManager: tokenB not available"); require(userPositions[msg.sender].length < ISettings(settingsAddress).getParameterValue("MaximumNumberOfLeveragedPositions"), "LeveragedLiquidityPositionManager: cannot exceed maximum number of leveraged positions"); address pair = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB); if (positionIndexes[msg.sender][pair] > 0) { _combinePositions(positionIndexes[msg.sender][pair].sub(1), collateral, amountToBorrow); } { _openPosition(tokenA, tokenB, collateral, amountToBorrow, farmAddress); positionIndexes[msg.sender][pair] = numberOfLeveragedPositions; } }
2,548,264
./full_match/43114/0x465eC7aD0C007721E83048C3d91e0Edb6A5F0b06/sources/avax.sol
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; } }
4,513,578
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; import "ds-test/test.sol"; import "./contracts/ERC721.sol"; import "./utils/Ownable.sol"; import "./utils/ECDSA.sol"; import "./utils/Counters.sol"; contract ZombsteinDapp is ERC721, Ownable { using ECDSA for bytes32; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenSupply; uint8 public constant teamAmount = 8; uint8 public constant internalWitholdLimit = 80; uint16 public constant preSaleAmount = 2200; uint16 public constant publicSaleAmount = 6600; uint16 public constant maxAmount = teamAmount + internalWitholdLimit + preSaleAmount + publicSaleAmount; uint64 public constant price = 0.08 ether; uint8 public constant maxPerTx = 5; uint16 public minted = 0; mapping(address => bool) public presalerList; mapping(address => uint256) public presalerListPurchases; mapping(string => bool) private _usedNonces; string private _contractURI; string private _tokenBaseURI = ""; address private _signerAddress = 0x02E1a5869E4649AEd2D8b92298D01e13d4236554; string public proof; uint256 public giftedAmount = 0; uint256 public presaleAmountMinted = 0; uint256 public publicAmountMinted = 0; uint256 public presalePurchaseLimit = 5; bool public isPresaleLive = false; bool public isSaleLive = false; bool public isLocked = true; constructor() ERC721("Zombstein", "ZOMB") {} modifier notLocked { require(!isLocked, "Contract metadata methods are locked"); _; } function addToPresaleList(address[] calldata userEntries) external onlyOwner { for(uint256 i = 0; i < userEntries.length; i++) { address userEntry = userEntries[i]; require(userEntry != address(0), "null address"); require(!presalerList[userEntry], "duplicate entry"); presalerList[userEntry] = true; } } function isInPresaleList(address presaler) external view returns (bool) { return presalerList[presaler]; } function removeFromPresaleList(address[] calldata userEntries) external onlyOwner { for (uint256 i = 0; i < userEntries.length; i++) { address userEntry = userEntries[i]; require(userEntry != address(0), "null address"); presalerList[userEntry] = false; } } /// @dev Hashes the frontend info /// @param sender The backend of the frontend that does the second signature /// @param qty Number of tokens to mint for a specific user /// @param nonce The random nonce generated by the backend server function hashTransaction(address sender, uint256 qty, string memory nonce) public returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender, qty, nonce)))); } /// @dev If the recovered public key did not match the _signerAddress variable, the function would immediately revert execution because it wasnโ€™t invoked through our flow, saving gas if someone did attempt to directly invoke the contract method. /// @param hash keccak256 hash contains the ABI encoded user address, quantity to mint, and nonce which is a randomly generated string with a length of 8 /// @param signature signature generated by the signer /// @return True if the signer address is the same as the one in the contract function matchAddressSigner(bytes32 hash, bytes memory signature) public view returns (bool) { // recover the public key used to sign the hash return _signerAddress == hash.toEthSignedMessageHash().recover(signature); } /// @dev Mints a token for a public minter, lots of requirements /// @param hash keccak256 hash contains the ABI encoded user address, quantity to mint, and nonce which is a randomly generated string with a length of 8 /// @param signature Signature from the frontend that contains the user's address and the nonce- what are the parameters of the signature from the frontend? /// @param nonce Of the user function mint(bytes32 hash, bytes memory signature, string memory nonce, uint256 tokenQuantity) external payable returns (bool) { require(isSaleLive, "Sale is not live"); require(!isPresaleLive, "Only whitelisted, presale members are allowed to buy tokens right now"); require(matchAddressSigner(hash, signature), "Direct mint is disallowed"); require(!_usedNonces[nonce], "Nonce already used"); require(hashTransaction(msg.sender, tokenQuantity, nonce) == hash, "Invalid transaction hash"); require(_tokenSupply.current() < maxAmount, "Max amount exceeded"); require(publicAmountMinted + tokenQuantity <= publicSaleAmount, "Public sale amount exceeded"); require(tokenQuantity <= maxPerTx, "Max amount per transaction exceeded"); require(price * tokenQuantity <= msg.value, "Not enough ether"); for (uint16 i = 0; i < tokenQuantity; i++) { publicAmountMinted++; _tokenSupply.increment(); _safeMint(msg.sender, _tokenSupply.current()); } _usedNonces[nonce] = true; return true; } /// @dev Mints a token for a presale member /// @param hash keccak256 hash contains the ABI encoded user address, quantity to mint, and nonce which is a randomly generated string with a length of 8 /// @param signature Signature from the frontend that contains the user's address and the nonce- what are the parameters of the signature from the frontend? /// @param nonce Of the user function presaleMint(bytes32 hash, bytes memory signature, string memory nonce, uint256 tokenQuantity) external payable returns (bool) { require(!isPresaleLive && isSaleLive, "Presale is not live"); require(presalerList[msg.sender], "Only presale members are allowed to buy tokens right now"); require(!_usedNonces[nonce], "Nonce already used"); require(matchAddressSigner(hash, signature), "Direct mint is disallowed"); require(_tokenSupply.current() < maxAmount, "NFTs are sold out!"); require(presalerListPurchases[msg.sender] + tokenQuantity <= presalePurchaseLimit, "Cannot mint more than your allocated amount"); require(price * tokenQuantity <= msg.value, "Not enough ether sent to purchase NFTs"); for (uint16 i = 0; i < tokenQuantity; i++) { presaleAmountMinted++; presalerListPurchases[msg.sender]++; _tokenSupply.increment(); _safeMint(msg.sender, _tokenSupply.current()); } _usedNonces[nonce] = true; return true; } /// @dev Need to compile list of gift receiver addresses before calling this function /// @param giftReceivers Array of addresses to receive the gift function gift(address[] calldata giftReceivers) external onlyOwner { require(_tokenSupply.current() + giftReceivers.length <= maxAmount, "Max amount exceeded"); require(giftedAmount + giftReceivers.length <= internalWitholdLimit, "No more gifts left"); for (uint16 i = 0; i < giftReceivers.length; i++) { giftedAmount++; _safeMint(giftReceivers[i], _tokenSupply.current()); } } /// @dev Gift multiple NFTs to an address /// @param giftReceiver Address to receive the gift, set as uint8 to help control limit to be below 256 per tx. Will limit if exploited /// @param number Number of NFTs to gift the individual function giftMultipleNFTs(address giftReceiver, uint8 number) external onlyOwner { require(_tokenSupply.current() + number <= maxAmount, "Max amount exceeded"); require(giftedAmount + number <= internalWitholdLimit, "No more gifts left"); for (uint8 i = 0; i < number; i++) { giftedAmount++; _safeMint(giftReceiver, _tokenSupply.current()); } } function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } function lockMetadata() external onlyOwner { isLocked = true; } function togglePresaleStatus() external onlyOwner { isPresaleLive = !isPresaleLive; } function toggleMainSaleStatus() external onlyOwner { isSaleLive = !isSaleLive; } function setSignerAddress(address addr) external onlyOwner { _signerAddress = addr; } function setProvenanceHash(string calldata hash) external onlyOwner notLocked { proof = hash; } function setContractURI(string calldata uri) external onlyOwner notLocked { _contractURI = uri; } function setTokenBaseURI(string calldata uri) external onlyOwner notLocked { _tokenBaseURI = uri; } function isPresaler(address addr) external view returns (bool) { return presalerList[addr]; } //////////////////////// @dev Getters //////////////////////// function presalePurchasedCount(address addr) external view returns (uint256) { return presalerListPurchases[addr]; } function getNumberOfTokensMinted() public view returns (uint256) { return _tokenSupply.current(); } function getContractURI() public view returns (string memory) { return _contractURI; } function getTokenBaseURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } function getIsPresaleLive() public view returns (bool) { return isPresaleLive; } function getGiftedAmount() public view returns (uint256) { return giftedAmount; } function increaseTokenSupply() external onlyOwner { _tokenSupply.increment(); } function getTokenSupply() public view returns (uint256) { return _tokenSupply.current(); } }
Gift multiple NFTs to an address giftReceiver Address to receive the gift, set as uint8 to help control limit to be below 256 per tx. Will limit if exploited number Number of NFTs to gift the individual
function giftMultipleNFTs(address giftReceiver, uint8 number) external onlyOwner { require(_tokenSupply.current() + number <= maxAmount, "Max amount exceeded"); require(giftedAmount + number <= internalWitholdLimit, "No more gifts left"); for (uint8 i = 0; i < number; i++) { giftedAmount++; _safeMint(giftReceiver, _tokenSupply.current()); } }
12,898,755
./partial_match/1/0xA53de764935d71968c7B5d311E6E76Ba22109a11/sources/DharmaTradeReserveV17ImplementationStaging.sol
Get the balance of this contract of the provided token before transferring. Transfer the token from the caller and revert on failure.
function tradeTokenForTokenWithFeeOnTransferSpecifyingFee( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 quotedTokenReceivedAmountAfterTransferFee, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensBought) { uint256 balanceBeforeTransferIn = tokenProvided.balanceOf(address(this)); _transferInToken(tokenProvided, msg.sender, tokenProvidedAmount); uint256 tokenProvidedAmountAfterTransferFee = tokenProvided.balanceOf( address(this) ).sub(balanceBeforeTransferIn); totalTokensBought = _tradeTokenForTokenWithFeeOnTransfer( msg.sender, tokenProvided, tokenReceived, tokenProvidedAmount, tokenProvidedAmountAfterTransferFee, quotedTokenReceivedAmount, quotedTokenReceivedAmountAfterTransferFee, maximumFeeAmount, deadline, routeThroughEther ); }
9,400,943
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface Migratable { function migrateTo(address user, address token, uint256 amount) payable external; } /* * @title Solidity Bytes Arrays Utils * @author Gonรงalo Sรก <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } /** * @title Serializable Migration * @author Ben Huang * @notice Let migration support serialization and deserialization */ contract SerializableMigration { using SafeMath for uint256; using BytesLib for bytes; uint constant public MIGRATION_1_SIZE = 24; uint constant public TOKENID_SIZE = 2; uint constant public SIGNATURE_SIZE = 65; uint8 constant internal _MASK_IS_ETH = 0x01; /** * @notice Get target address from the serialized migration data * @param ser_data Serialized migration data * @return target Target contract address */ function _getMigrationTarget(bytes memory ser_data) internal pure returns (address target) { target = ser_data.toAddress(ser_data.length - 20); } /** * @notice Get user ID from the serialized migration data * @param ser_data Serialized migration data * @return userID User ID */ function _getMigrationUserID(bytes memory ser_data) internal pure returns (uint256 userID) { userID = ser_data.toUint32(ser_data.length - 24); } /** * @notice Get token count * @param ser_data Serialized migration data * @return n The migrate token amount */ function _getMigrationCount(bytes memory ser_data) internal pure returns (uint256 n) { n = (ser_data.length - SIGNATURE_SIZE - MIGRATION_1_SIZE) / 2; } /** * @notice Get token ID to be migrated * @param ser_data Serialized migration data * @param index The index of token ID to be migrated * @return tokenID The token ID to be migrated */ function _getMigrationTokenID(bytes memory ser_data, uint index) internal pure returns (uint256 tokenID) { require(index < _getMigrationCount(ser_data)); tokenID = ser_data.toUint16(ser_data.length - MIGRATION_1_SIZE - (TOKENID_SIZE.mul(index + 1))); } /** * @notice Get v from the serialized migration data * @param ser_data Serialized migration data * @return v Signature v */ function _getMigrationV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(SIGNATURE_SIZE - 1); } /** * @notice Get r from the serialized migration data * @param ser_data Serialized migration data * @return r Signature r */ function _getMigrationR(bytes memory ser_data) internal pure returns (bytes32 r) { r = ser_data.toBytes32(SIGNATURE_SIZE - 33); } /** * @notice Get s from the serialized migration data * @param ser_data Serialized migration data * @return s Signature s */ function _getMigrationS(bytes memory ser_data) internal pure returns (bytes32 s) { s = ser_data.toBytes32(SIGNATURE_SIZE - 65); } /** * @notice Get hash from the serialized migration data * @param ser_data Serialized migration data * @return hash Migration hash without signature */ function _getMigrationHash(bytes memory ser_data) internal pure returns (bytes32 hash) { hash = keccak256(ser_data.slice(65, ser_data.length - SIGNATURE_SIZE)); } } /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n รท 2 + 1, and for v in (282): v โˆˆ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } /** * 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(address(this), spender) == 0)); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must equal true). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } /** * @title Serializable Order * @author Ben Huang * @notice Let order support serialization and deserialization */ contract SerializableOrder { using SafeMath for uint256; using BytesLib for bytes; uint constant public ORDER_SIZE = 206; uint constant public UNSIGNED_ORDER_SIZE = 141; uint8 constant internal _MASK_IS_BUY = 0x01; uint8 constant internal _MASK_IS_MAIN = 0x02; /** * @notice Get user ID from the serialized order data * @param ser_data Serialized order data * @return userID User ID */ function _getOrderUserID(bytes memory ser_data) internal pure returns (uint256 userID) { userID = ser_data.toUint32(ORDER_SIZE - 4); } /** * @notice Get base token ID from the serialized order data * @param ser_data Serialized order data * @return tokenBase Base token ID */ function _getOrderTokenIDBase(bytes memory ser_data) internal pure returns (uint256 tokenBase) { tokenBase = ser_data.toUint16(ORDER_SIZE - 6); } /** * @notice Get base token amount from the serialized order data * @param ser_data Serialized order data * @return amountBase Base token amount */ function _getOrderAmountBase(bytes memory ser_data) internal pure returns (uint256 amountBase) { amountBase = ser_data.toUint(ORDER_SIZE - 38); } /** * @notice Get quote token ID from the serialized order data * @param ser_data Serialized order data * @return tokenQuote Quote token ID */ function _getOrderTokenIDQuote(bytes memory ser_data) internal pure returns (uint256 tokenQuote) { tokenQuote = ser_data.toUint16(ORDER_SIZE - 40); } /** * @notice Get quote token amount from the serialized order data * @param ser_data Serialized order data * @return amountQuote Quote token amount */ function _getOrderAmountQuote(bytes memory ser_data) internal pure returns (uint256 amountQuote) { amountQuote = ser_data.toUint(ORDER_SIZE - 72); } /** * @notice Check if the order is a buy order * @param ser_data Serialized order data * @return fBuy Is buy order or not */ function _isOrderBuy(bytes memory ser_data) internal pure returns (bool fBuy) { fBuy = (ser_data.toUint8(ORDER_SIZE - 73) & _MASK_IS_BUY != 0); } /** * @notice Check if the fee is paid by main token * @param ser_data Serialized order data * @return fMain Is the fee paid in main token or not */ function _isOrderFeeMain(bytes memory ser_data) internal pure returns (bool fMain) { fMain = (ser_data.toUint8(ORDER_SIZE - 73) & _MASK_IS_MAIN != 0); } /** * @notice Get nonce from the serialized order data * @param ser_data Serialized order data * @return nonce Nonce */ function _getOrderNonce(bytes memory ser_data) internal pure returns (uint256 nonce) { nonce = ser_data.toUint32(ORDER_SIZE - 77); } /** * @notice Get trading fee from the serialized order data * @param ser_data Serialized order data * @return fee Fee amount */ function _getOrderTradeFee(bytes memory ser_data) internal pure returns (uint256 tradeFee) { tradeFee = ser_data.toUint(ORDER_SIZE - 109); } /** * @notice Get gas fee from the serialized order data * @param ser_data Serialized order data * @return fee Fee amount */ function _getOrderGasFee(bytes memory ser_data) internal pure returns (uint256 gasFee) { gasFee = ser_data.toUint(ORDER_SIZE - 141); } /** * @notice Get v from the serialized order data * @param ser_data Serialized order data * @return v Signature v */ function _getOrderV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(ORDER_SIZE - 142); } /** * @notice Get r from the serialized order data * @param ser_data Serialized order data * @return r Signature r */ function _getOrderR(bytes memory ser_data) internal pure returns (bytes32 r) { r = ser_data.toBytes32(ORDER_SIZE - 174); } /** * @notice Get s from the serialized order data * @param ser_data Serialized order data * @return s Signature s */ function _getOrderS(bytes memory ser_data) internal pure returns (bytes32 s) { s = ser_data.toBytes32(ORDER_SIZE - 206); } /** * @notice Get hash from the serialized order data * @param ser_data Serialized order data * @return hash Order hash without signature */ function _getOrderHash(bytes memory ser_data) internal pure returns (bytes32 hash) { hash = keccak256(ser_data.slice(65, UNSIGNED_ORDER_SIZE)); } /** * @notice Fetch the serialized order data with the given index * @param ser_data Serialized order data * @param index The index of order to be fetched * @return order_data The fetched order data */ function _getOrder(bytes memory ser_data, uint index) internal pure returns (bytes memory order_data) { require(index < _getOrderCount(ser_data)); order_data = ser_data.slice(ORDER_SIZE.mul(index), ORDER_SIZE); } /** * @notice Count the order amount * @param ser_data Serialized order data * @return amount Order amount */ function _getOrderCount(bytes memory ser_data) internal pure returns (uint256 amount) { amount = ser_data.length.div(ORDER_SIZE); } } /** * @title Serializable Withdrawal * @author Ben Huang * @notice Let withdrawal support serialization and deserialization */ contract SerializableWithdrawal { using SafeMath for uint256; using BytesLib for bytes; uint constant public WITHDRAWAL_SIZE = 140; uint constant public UNSIGNED_WITHDRAWAL_SIZE = 75; uint8 constant internal _MASK_IS_ETH = 0x01; /** * @notice Get user ID from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return userID User ID */ function _getWithdrawalUserID(bytes memory ser_data) internal pure returns (uint256 userID) { userID = ser_data.toUint32(WITHDRAWAL_SIZE - 4); } /** * @notice Get token ID from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return tokenID Withdrawal token ID */ function _getWithdrawalTokenID(bytes memory ser_data) internal pure returns (uint256 tokenID) { tokenID = ser_data.toUint16(WITHDRAWAL_SIZE - 6); } /** * @notice Get amount from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return amount Withdrawal token amount */ function _getWithdrawalAmount(bytes memory ser_data) internal pure returns (uint256 amount) { amount = ser_data.toUint(WITHDRAWAL_SIZE - 38); } /** * @notice Check if the fee is paid by main token * @param ser_data Serialized withdrawal data * @return fETH Is the fee paid in ETH or DGO */ function _isWithdrawalFeeETH(bytes memory ser_data) internal pure returns (bool fFeeETH) { fFeeETH = (ser_data.toUint8(WITHDRAWAL_SIZE - 39) & _MASK_IS_ETH != 0); } /** * @notice Get nonce from the serialized withrawal data * @param ser_data Serialized withdrawal data * @return nonce Nonce */ function _getWithdrawalNonce(bytes memory ser_data) internal pure returns (uint256 nonce) { nonce = ser_data.toUint32(WITHDRAWAL_SIZE - 43); } /** * @notice Get fee amount from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return fee Fee amount */ function _getWithdrawalFee(bytes memory ser_data) internal pure returns (uint256 fee) { fee = ser_data.toUint(WITHDRAWAL_SIZE - 75); } /** * @notice Get v from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return v Signature v */ function _getWithdrawalV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(WITHDRAWAL_SIZE - 76); } /** * @notice Get r from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return r Signature r */ function _getWithdrawalR(bytes memory ser_data) internal pure returns (bytes32 r) { r = ser_data.toBytes32(WITHDRAWAL_SIZE - 108); } /** * @notice Get s from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return s Signature s */ function _getWithdrawalS(bytes memory ser_data) internal pure returns (bytes32 s) { s = ser_data.toBytes32(WITHDRAWAL_SIZE - 140); } /** * @notice Get hash from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return hash Withdrawal hash without signature */ function _getWithdrawalHash(bytes memory ser_data) internal pure returns (bytes32 hash) { hash = keccak256(ser_data.slice(65, UNSIGNED_WITHDRAWAL_SIZE)); } } /** * @title Dinngo * @author Ben Huang * @notice Main exchange contract for Dinngo */ contract Dinngo is SerializableOrder, SerializableWithdrawal, SerializableMigration { // Storage alignment address private _owner; mapping (address => bool) private admins; uint256 private _nAdmin; uint256 private _nLimit; // end using ECDSA for bytes32; using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public processTime; mapping (address => mapping (address => uint256)) public balances; mapping (bytes32 => uint256) public orderFills; mapping (uint256 => address payable) public userID_Address; mapping (uint256 => address) public tokenID_Address; mapping (address => uint256) public userRanks; mapping (address => uint256) public tokenRanks; mapping (address => uint256) public lockTimes; event AddUser(uint256 userID, address indexed user); event AddToken(uint256 tokenID, address indexed token); event Deposit(address token, address indexed user, uint256 amount, uint256 balance); event Withdraw( address token, address indexed user, uint256 amount, uint256 balance, address tokenFee, uint256 amountFee ); event Trade( address indexed user, bool isBuy, address indexed tokenBase, uint256 amountBase, address indexed tokenQuote, uint256 amountQuote, address tokenFee, uint256 amountFee ); event Lock(address indexed user, uint256 lockTime); event Unlock(address indexed user); /** * @dev All ether directly sent to contract will be refunded */ function() external payable { revert(); } /** * @notice Add the address to the user list. Event AddUser will be emitted * after execution. * @dev Record the user list to map the user address to a specific user ID, in * order to compact the data size when transferring user address information * @dev id should be less than 2**32 * @param id The user id to be assigned * @param user The user address to be added */ function addUser(uint256 id, address payable user) external { require(user != address(0)); require(userRanks[user] == 0); require(id < 2**32); if (userID_Address[id] == address(0)) userID_Address[id] = user; else require(userID_Address[id] == user); userRanks[user] = 1; emit AddUser(id, user); } /** * @notice Remove the address from the user list. * @dev The user rank is set to 0 to remove the user. * @param user The user address to be added */ function removeUser(address user) external { require(user != address(0)); require(userRanks[user] != 0); userRanks[user] = 0; } /** * @notice Update the rank of user. Can only be called by owner. * @param user The user address * @param rank The rank to be assigned */ function updateUserRank(address user, uint256 rank) external { require(user != address(0)); require(rank != 0); require(userRanks[user] != 0); require(userRanks[user] != rank); userRanks[user] = rank; } /** * @notice Add the token to the token list. Event AddToken will be emitted * after execution. * @dev Record the token list to map the token contract address to a specific * token ID, in order to compact the data size when transferring token contract * address information * @dev id should be less than 2**16 * @param id The token id to be assigned * @param token The token contract address to be added */ function addToken(uint256 id, address token) external { require(token != address(0)); require(tokenRanks[token] == 0); require(id < 2**16); if (tokenID_Address[id] == address(0)) tokenID_Address[id] = token; else require(tokenID_Address[id] == token); tokenRanks[token] = 1; emit AddToken(id, token); } /** * @notice Remove the token to the token list. * @dev The token rank is set to 0 to remove the token. * @param token The token contract address to be removed. */ function removeToken(address token) external { require(token != address(0)); require(tokenRanks[token] != 0); tokenRanks[token] = 0; } /** * @notice Update the rank of token. Can only be called by owner. * @param token The token contract address. * @param rank The rank to be assigned. */ function updateTokenRank(address token, uint256 rank) external { require(token != address(0)); require(rank != 0); require(tokenRanks[token] != 0); require(tokenRanks[token] != rank); tokenRanks[token] = rank; } /** * @notice The deposit function for ether. The ether that is sent with the function * call will be deposited. The first time user will be added to the user list. * Event Deposit will be emitted after execution. */ function deposit() external payable { require(!_isLocking(msg.sender)); require(msg.value > 0); balances[address(0)][msg.sender] = balances[address(0)][msg.sender].add(msg.value); emit Deposit(address(0), msg.sender, msg.value, balances[address(0)][msg.sender]); } /** * @notice The deposit function for tokens. The first time user will be added to * the user list. Event Deposit will be emitted after execution. * @param token Address of the token contract to be deposited * @param amount Amount of the token to be depositied */ function depositToken(address token, uint256 amount) external { require(token != address(0)); require(!_isLocking(msg.sender)); require(_isValidToken(token)); require(amount > 0); balances[token][msg.sender] = balances[token][msg.sender].add(amount); emit Deposit(token, msg.sender, amount, balances[token][msg.sender]); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); } /** * @notice The withdraw function for ether. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param amount The amount to be withdrawn. */ function withdraw(uint256 amount) external { require(_isLocked(msg.sender)); require(_isValidUser(msg.sender)); require(amount > 0); balances[address(0)][msg.sender] = balances[address(0)][msg.sender].sub(amount); emit Withdraw(address(0), msg.sender, amount, balances[address(0)][msg.sender], address(0), 0); msg.sender.transfer(amount); } /** * @notice The withdraw function for tokens. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param token The token contract address to be withdrawn. * @param amount The token amount to be withdrawn. */ function withdrawToken(address token, uint256 amount) external { require(token != address(0)); require(_isLocked(msg.sender)); require(_isValidUser(msg.sender)); require(_isValidToken(token)); require(amount > 0); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); emit Withdraw(token, msg.sender, amount, balances[token][msg.sender], address(0), 0); IERC20(token).safeTransfer(msg.sender, amount); } /** * @notice The withdraw function that can only be triggered by owner. * Event Withdraw will be emitted after execution. * @param withdrawal The serialized withdrawal data */ function withdrawByAdmin(bytes calldata withdrawal) external { address payable user = userID_Address[_getWithdrawalUserID(withdrawal)]; address wallet = userID_Address[0]; address token = tokenID_Address[_getWithdrawalTokenID(withdrawal)]; uint256 amount = _getWithdrawalAmount(withdrawal); uint256 amountFee = _getWithdrawalFee(withdrawal); address tokenFee = _isWithdrawalFeeETH(withdrawal)? address(0) : tokenID_Address[1]; uint256 balance = balances[token][user].sub(amount); require(_isValidUser(user)); _verifySig( user, _getWithdrawalHash(withdrawal), _getWithdrawalR(withdrawal), _getWithdrawalS(withdrawal), _getWithdrawalV(withdrawal) ); if (tokenFee == token) { balance = balance.sub(amountFee); } else { balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee); } balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee); balances[token][user] = balance; emit Withdraw(token, user, amount, balance, tokenFee, amountFee); if (token == address(0)) { user.transfer(amount); } else { IERC20(token).safeTransfer(user, amount); } } /** * @notice The migrate function the can only triggered by admin. * Event Migrate will be emitted after execution. * @param migration The serialized migration data */ function migrateByAdmin(bytes calldata migration) external { address target = _getMigrationTarget(migration); address user = userID_Address[_getMigrationUserID(migration)]; uint256 nToken = _getMigrationCount(migration); require(_isValidUser(user)); _verifySig( user, _getMigrationHash(migration), _getMigrationR(migration), _getMigrationS(migration), _getMigrationV(migration) ); for (uint i = 0; i < nToken; i++) { address token = tokenID_Address[_getMigrationTokenID(migration, i)]; uint256 balance = balances[token][user]; require(balance != 0); balances[token][user] = 0; if (token == address(0)) { Migratable(target).migrateTo.value(balance)(user, token, balance); } else { IERC20(token).approve(target, balance); Migratable(target).migrateTo(user, token, balance); } } } /** * @notice The settle function for orders. First order is taker order and the followings * are maker orders. * @param orders The serialized orders. */ function settle(bytes calldata orders) external { // Deal with the order list uint256 nOrder = _getOrderCount(orders); // Get the first order as the taker order bytes memory takerOrder = _getOrder(orders, 0); uint256 totalAmountBase = _getOrderAmountBase(takerOrder); uint256 takerAmountBase = totalAmountBase.sub(orderFills[_getOrderHash(takerOrder)]); uint256 fillAmountQuote = 0; uint256 restAmountBase = takerAmountBase; bool fBuy = _isOrderBuy(takerOrder); // Parse maker orders for (uint i = 1; i < nOrder; i++) { // Get ith order as the maker order bytes memory makerOrder = _getOrder(orders, i); require(fBuy != _isOrderBuy(makerOrder)); uint256 makerAmountBase = _getOrderAmountBase(makerOrder); // Calculate the amount to be executed uint256 amountBase = makerAmountBase.sub(orderFills[_getOrderHash(makerOrder)]); amountBase = amountBase <= restAmountBase? amountBase : restAmountBase; uint256 amountQuote = _getOrderAmountQuote(makerOrder).mul(amountBase).div(makerAmountBase); restAmountBase = restAmountBase.sub(amountBase); fillAmountQuote = fillAmountQuote.add(amountQuote); // Trade amountBase and amountQuote for maker order _trade(amountBase, amountQuote, makerOrder); } // Sum the trade amount and check takerAmountBase = takerAmountBase.sub(restAmountBase); if (fBuy) { require(fillAmountQuote.mul(totalAmountBase) <= _getOrderAmountQuote(takerOrder).mul(takerAmountBase)); } else { require(fillAmountQuote.mul(totalAmountBase) >= _getOrderAmountQuote(takerOrder).mul(takerAmountBase)); } // Trade amountBase and amountQuote for taker order _trade(takerAmountBase, fillAmountQuote, takerOrder); } /** * @notice Announce lock of the sender */ function lock() external { require(!_isLocking(msg.sender)); lockTimes[msg.sender] = now.add(processTime); emit Lock(msg.sender, lockTimes[msg.sender]); } /** * @notice Unlock the sender */ function unlock() external { require(_isLocking(msg.sender)); lockTimes[msg.sender] = 0; emit Unlock(msg.sender); } /** * @notice Change the processing time of locking the user address */ function changeProcessTime(uint256 time) external { require(processTime != time); processTime = time; } /** * @notice Process the trade by the providing information * @param amountBase The provided amount to be traded * @param amountQuote The amount to be requested * @param order The order that triggered the trading */ function _trade(uint256 amountBase, uint256 amountQuote, bytes memory order) internal { require(amountBase != 0); // Get parameters address user = userID_Address[_getOrderUserID(order)]; address wallet = userID_Address[0]; bytes32 hash = _getOrderHash(order); address tokenQuote = tokenID_Address[_getOrderTokenIDQuote(order)]; address tokenBase = tokenID_Address[_getOrderTokenIDBase(order)]; address tokenFee; uint256 amountFee = _getOrderTradeFee(order).mul(amountBase).div(_getOrderAmountBase(order)); require(_isValidUser(user)); // Trade and fee setting if (orderFills[hash] == 0) { _verifySig(user, hash, _getOrderR(order), _getOrderS(order), _getOrderV(order)); amountFee = amountFee.add(_getOrderGasFee(order)); } bool fBuy = _isOrderBuy(order); if (fBuy) { balances[tokenQuote][user] = balances[tokenQuote][user].sub(amountQuote); if (_isOrderFeeMain(order)) { tokenFee = tokenBase; balances[tokenBase][user] = balances[tokenBase][user].add(amountBase).sub(amountFee); balances[tokenBase][wallet] = balances[tokenBase][wallet].add(amountFee); } else { tokenFee = tokenID_Address[1]; balances[tokenBase][user] = balances[tokenBase][user].add(amountBase); balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee); balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee); } } else { balances[tokenBase][user] = balances[tokenBase][user].sub(amountBase); if (_isOrderFeeMain(order)) { tokenFee = tokenQuote; balances[tokenQuote][user] = balances[tokenQuote][user].add(amountQuote).sub(amountFee); balances[tokenQuote][wallet] = balances[tokenQuote][wallet].add(amountFee); } else { tokenFee = tokenID_Address[1]; balances[tokenQuote][user] = balances[tokenQuote][user].add(amountQuote); balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee); balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee); } } // Order fill orderFills[hash] = orderFills[hash].add(amountBase); emit Trade ( user, fBuy, tokenBase, amountBase, tokenQuote, amountQuote, tokenFee, amountFee ); } /** * @dev Check if the user is valid * @param user The user address to be checked. */ function _isValidUser(address user) internal view returns (bool) { return userRanks[user] != 0; } /** * @dev Check if the token is valid * @param token The token address to be checked. */ function _isValidToken(address token) internal view returns (bool) { return tokenRanks[token] != 0; } /** * @notice Verify if the data is signed by the given user and signature * @param user The signing user * @param hash The data hash to be verified * @param r The signature R * @param s The signature S * @param v The signature V */ function _verifySig(address user, bytes32 hash, bytes32 r, bytes32 s, uint8 v) internal pure { // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); address sigAddr = ecrecover(hash.toEthSignedMessageHash(), v, r, s); require(user == sigAddr); } /** * @notice Return if the give user has announced lock * @param user The user address to be queried * @return Query result */ function _isLocking(address user) internal view returns (bool) { return lockTimes[user] > 0; } /** * @notice Return if the user is locked * @param user The user address to be queried */ function _isLocked(address user) internal view returns (bool) { return _isLocking(user) && lockTimes[user] < now; } }
Check if the fee is paid by main token ser_data Serialized withdrawal data return fETH Is the fee paid in ETH or DGO/
function _isWithdrawalFeeETH(bytes memory ser_data) internal pure returns (bool fFeeETH) { fFeeETH = (ser_data.toUint8(WITHDRAWAL_SIZE - 39) & _MASK_IS_ETH != 0); }
15,834,846
./partial_match/42/0xC31518D4fbA20E3618F6e7B24D1Bada43837Ed45/sources/GebProxyDebtAuctionActions.sol
Joins COIN amount into the safeEngine Paybacks debt to the SAFE and unlocks token amount from it Moves the amount from the SAFE handler to proxy's address Exits token amount to the user's wallet as a token
function repayAllDebtAndFreeTokenCollateral( address manager, address collateralJoin, address coinJoin, uint safe, uint collateralAmount ) public { address safeEngine = ManagerLike(manager).safeEngine(); address safeHandler = ManagerLike(manager).safes(safe); bytes32 collateralType = ManagerLike(manager).collateralTypes(safe); (, uint generatedDebt) = SAFEEngineLike(safeEngine).safes(collateralType, safeHandler); coinJoin_join(coinJoin, safeHandler, _getRepaidAlDebt(safeEngine, safeHandler, safeHandler, collateralType)); uint collateralWad = convertTo18(collateralJoin, collateralAmount); modifySAFECollateralization( manager, safe, -toInt(collateralWad), -int(generatedDebt) ); transferCollateral(manager, safe, address(this), collateralWad); CollateralJoinLike(collateralJoin).exit(msg.sender, collateralAmount); }
3,338,829
/** *Submitted for verification at Etherscan.io on 2022-02-19 */ // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: ERC721A.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721A: balance query for the zero address" ); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721A: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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( "ERC721A: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: Shroomates.sol pragma solidity ^0.8.0; //@@@@@@@*..,@@@@@@@@@@@@@@@@@@....*[emailย protected]@@@@@@@**@*@@@@@@@@@@@@..*@@,,@([emailย protected]@@@@@ //@&[emailย protected]@@@[emailย protected]@@[emailย protected]%@@@@@[emailย protected]@@@@@@[emailย protected]@@@ //@@......#[emailย protected]%@@@....../@[emailย protected]%@@@@@[emailย protected]@@@@@@*[emailย protected]@%[emailย protected]%@@ //@@,,,,,@@&@@@@@@@@@@@[emailย protected]#[emailย protected]%@@@@[emailย protected]%@[emailย protected]%@@@@@@[emailย protected]@@@[emailย protected]@%@@ //@@*&***@%@(***,,@@@@@,,,,,,,,,,,,,@@%@@@#,@,,@@@,@,,@@@@@@@,*,*********%@&@@ //@@/(%///@@@/////@@@@@@///&////****@@@@@@/*////*/////@@&@@@@///////////@@@@@@ //@@/&///////////&@&@@@//////@#////(@@@@@/////@#(/@/////@@@@@/@////@//////@@@@ //@@@@(//////////@@%@@@%//////@@@///@@@@@//%///(@@@/////#@@@@////@@@@/////@@@@ //@@@@@@/&@@#/@@@%@@@@@@@@@@/@%@@@/@@@%@@@@&@@@&%@@@@(@@&%@@@@///@@@@@//@@%@@@ //@@@@@@@@@%@@@@@@@@@@@@@@@@@@@@@@(@%@@@@@@@@@%@@@@@@&@&@@@@@@@@%@@@@@@@@@@@@@ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@@@@@@@@,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@@@([emailย protected]@@@@@@@@@@....%...*@@@@@@@[emailย protected]@@@**@@[emailย protected]@@@ //@@@@(..%[emailย protected]@@@@@@@@@@[emailย protected]@@@@@@@@[emailย protected]@@@*,@@[emailย protected]@@@ //@@@@..,....*@@@@@@@@@@@[emailย protected](.*[emailย protected]&@@@@@@....#@....([emailย protected]@@,@([emailย protected]@.(.%@@@@ //@@@@%,,,,,,@@@@@@@@@@@,,,,@@@@,,,@@@@@@@,,,,,,,,,,,*@@**@%,,..,.,,,@@&@@@ //@@@@*******@%@@@@@@@@***(**/****(**&@@@@****@/@&&****@@@@@@@@&/,,,,,,@@@@ //@@@@@(@////(/&@/@@@@@////**%*******@@@@@@***#@@*&***%@@@@@@@@@@****%*@&@@ //@@@@%/////@/////(@&@%/////(@@@//////@@@@///////////@#@@@@///////////@@%@@ //@@@@//%@(//////@@%@@@@@#//@@%@@/#@/@@@@@//@%/(/@@@/@%@/@@///////&@/@@&@@@ //@@@@@@@@@@@@@@//@@@@@@@@/@%@@@@@@/@@@@@@@@@@@@/(%@@@@@/,@%/@@@//@@%@@@@@@ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%@@@@@@@@@@/@%@@@@@@@@@@@@@@@@@@@@@@@@ //%%%%%%%%%%%%%%%&%%%%&&&&&&%%&&&&&&&&&&&&%&&&&&&&&%&&&&&&%&%&&&&&&&&&&&&&&&%&&&%% //%&%%%%%%%%%%%%%%%%%%&%%%%&&%&%@@&@@%&&&&&&&&&&%%%%%%%%&%%&&&&&&&&&&&&&&%%%%%%&&% //%%%%%%%%%%%%%%%%%%%%%%@@@% &@@@@@ @@@@ .&&%%%&&%%%%%&&%&&&%&%%&%%&%%%%&%%& //%%%%%%%%%%%%%%%%%%, @@@/ *@@@@@ @@@# @. @&&%%&%&%%%&%%%%%%%%%%&&%%% //%%%%%%%%%%%%%%& &@@. [emailย protected]@@@[emailย protected]@@@@. [emailย protected] @@. @@@.&&%%&%%&&%&&&&&&&%%%%% //%%%%%%%%%%%%@@@&.(@@[emailย protected]@@@@[emailย protected]@@@,........ [emailย protected] [emailย protected]@@. %%&&%&%%&&&&&&%%%%%% //%%%%%%&%%%& ,@@@@@@*[emailย protected]@@@@(...#@@@@@#[emailย protected]# &@@@ (%&&&%&%%%%%%%%%%% //%%%%%%%%%&. [emailย protected]@@@@@....,*@@@@@@*...#@@@@@@@.......,#. @@@@ @@%%%%%%%%%%%%%% //%%%%%%%%%@@,[emailย protected]@@%%%%&%%%&%%%%&%%%%@&@@@@@@@@([emailย protected]@@. #@@&%%%%%%%%%%%% //&&&&&%%%%@@@,[emailย protected]&%%%&%%%%%%%%%%%%%%%%%%%%@@@@@@@@&[emailย protected]@@ @@& #%%%%%%%%%% //%%%%%%%%%@@@@,..,%&%%%%&%%%%%&%&%%&%%&%%%%&%%&%@@@@@@@....%@@,. @@& &%%%%%%%%% //&&%%%%%%%&@@@@[emailย protected]&%%%%%%&%&%%&%%%&%%%%%%%%&%%%%%&@@@@@#..*@@...,@@ @%%%%%%%% //%&%&%%%%%%%@@@@[emailย protected]&%&%&%&*&%%*&%&%%%%%@%&%%%%%%%%%&&@@@@[emailย protected]#[emailย protected]@ @@@%%%%%%% //%%%%%%%%%%%%@@@,....%&%&%/ #%%%,,,,,,*,/,&%&%%%%&%%%%%@@@@[emailย protected]*[emailย protected] *@@@ @%%%%%% //%%%%%%%%%%%%%%@(......&&*%&/,,,, ( ,,,,((,%%%%&&%%%%&%(@@@&[emailย protected]@@ @@%%%%%% //%%%%%%%%%%%%%%%%([emailย protected]&*&%,,,,,,(&&/,*#/ //%&(@%%&&%%%%%@@@@*[emailย protected]@ @@@%%%%%% //*#%&&%%%%%%%%%%%%%%,..,@%(,,,,,@@@@*.#/ %//,#./%%%%%%%%%%%#@@@...(@@ @@,%%%%%%% //#/****/**%%%%%%%%%%%%%( *.(,,,,,(%(@@*/////,&,@&&%%&&%%%%%&[emailย protected]@@..(@@ /@. @%%%%%% //////*****///%&%%%%%%.%@%*,,,,,,,,,***////,,&&&&&%&%&&%%%%%%.,@@@.,@% &@ @%%%%%%% //////********//////&,, ,,,,,,,,&/*.&&%/,&%%/%%&&&&%&&%&%&(..%@@,[emailย protected], /%%%%%%%%% ///////%***///***/(,,,,,,,,,,,,,,,***////,% .&@@[emailย protected]@@@@@@@@@@&[emailย protected]@/[emailย protected] %%%%%%%%%%% ///////**#**%%***%,,,%.#&&/,,,,,,***# *%%%&*@@.*@@/...,@@@#..%@& .%%%%%%%%%%%%% //((/////*(///**,,,,,, (&&,,,,,/ .&. %@%@& .&%%%%%%&@#. [emailย protected]@@. #%%%%%%%%%%%%%%%%% //(***////**[emailย protected]&,#,,,,,,,%..*,*/%@##. . ,[emailย protected]%%****/******&%%%%%%%%%%%%%&#**(&/*&&&#* ///********/%/@*%.,,.&,,#* (,,,/@@**///*,//%/(*******%**/*&%%%%%%&%***//**//////// /////******@.%&@/,,.%*,,,,,*%#,***/////*,///(********///////*****************(/*** //&#//**********/(./*,,,,/@&,,,**//////,,**//////////////*****************//(((/** ///**/////////*****&#& #,,,,,,*//(////,,&***/*///////*********//////***////(((///* //***//****(((//**** &,,/*& %@* @,,&********//*******(#**//********//(((((//** //***/*****/((((/%(*****/&#&/*%@@%@ %,**********//*******//*************/((((//*** ///*******/(((((((//*******(,,,,*,&%//#%********////((////**************(((******* ///******//((((((((((///******///////(//#//((////////******************/((******** interface IGnarCoin { function burn(address _from, uint256 _amount) external; function updateReward(address _from, address _to) external; } contract Shroomates is ERC721A, Ownable, ReentrancyGuard { using Strings for uint256; using Address for address; string private baseURI; uint256 public maxSupply = 7777; uint256 public maxBuyable = 7700; uint256 public immutable maxPerAddressDuringMint; uint256 public price; uint256 public buffer; mapping(address => uint256) public genBalance; struct ShroomData { string name; } modifier ShroomOwner(uint256 ShroomId) { require( ownerOf(ShroomId) == msg.sender, "Cannot interact with a ShroomMate you do not own" ); _; } IGnarCoin public GnarCoin; uint256 public constant NAME_CHANGE_PRICE = 150 ether; mapping(uint256 => ShroomData) public shroomData; event NameChanged(uint256 ShroomId, string ShroomName); constructor( string memory name, string memory symbol, uint256 maxBatchSize_, uint256 collectionSize_, uint256 mintPrice_ ) //double check with gnar on these settings ERC721A(name, symbol, maxBatchSize_, collectionSize_) { maxPerAddressDuringMint = maxBatchSize_; price = mintPrice_; } function changeName(uint256 ShroomId, string memory newName) external ShroomOwner(ShroomId) { bytes memory n = bytes(newName); require(n.length > 0 && n.length < 25, "Invalid name length"); require( sha256(n) != sha256(bytes(shroomData[ShroomId].name)), "New name is same as current name" ); // GnarCoin.burn(msg.sender, NAME_CHANGE_PRICE); shroomData[ShroomId].name = newName; emit NameChanged(ShroomId, newName); } function setGnarCoin(address GnarCoinAddress) external onlyOwner { GnarCoin = IGnarCoin(GnarCoinAddress); } function mint(uint256 numberOfMints) public payable { uint256 maxSupplyBuff = maxBuyable + buffer; require( totalSupply() + numberOfMints <= maxSupplyBuff, "Purchase would exceed max supply of ShroomMate" ); //this line will make sure the user cannot buy anymore than {maxBatchSize_} require( numberMinted(msg.sender) + numberOfMints <= maxPerAddressDuringMint, "Limit number of mints to an amount set on contract configuration" ); require( msg.value >= price * numberOfMints, "Ether value sent is below the price" ); _safeMint(msg.sender, numberOfMints); genBalance[msg.sender]++; } function gift(uint256 numberOfMints, address _to) public onlyOwner { require( totalSupply() + numberOfMints <= maxSupply, "Purchase would exceed max supply of ShroomMate" ); buffer++; _safeMint(_to, numberOfMints); genBalance[msg.sender]++; } function walletOfOwner(address owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(owner, i); } return tokensId; } function transferFrom( address from, address to, uint256 tokenId ) public override { if (tokenId < maxSupply) { GnarCoin.updateReward(from, to); genBalance[from]--; genBalance[to]++; } ERC721A.transferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public override { if (tokenId < maxSupply) { GnarCoin.updateReward(from, to); genBalance[from]--; genBalance[to]++; } ERC721A.safeTransferFrom(from, to, tokenId, data); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setBaseURI(string memory uri) public onlyOwner { baseURI = uri; } function _baseURI() internal view override returns (string memory) { return baseURI; } function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } }
File: Shroomates.sol@@@@@@@..,@@@@@@@@@@@@@@@@@@....[emailย protected]@@@@@@@@@@@@@@@@@@@@..@@,,@([emailย protected]@@@@@@&[emailย protected]@@@[emailย protected]@@[emailย protected]%@@@@@[emailย protected]@@@@@@[emailย protected]@@@@@......[emailย protected]%@@@....../@[emailย protected]%@@@@@[emailย protected]@@@@@@[emailย protected]@%[emailย protected]%@@@@,,,,,@@&@@@@@@@@@@@[emailย protected][emailย protected]%@@@@[emailย protected]%@[emailย protected]%@@@@@@[emailย protected]@@@[emailย protected]@%@@@@&@%@(,,@@@@@,,,,,,,,,,,,,@@%@@@,@,,@@@,@,,@@@@@@@,,%@&@@@@/(%/@@@/@@@@@@/&@@@@@@//@@&@@@@/@@@@@@@@/&/&@&@@@@(@@@@@/@(/@/@@@@@/@@@@@@@@@@(@@%@@@%@@@/@@@@@%/(@@@/@@@@@@@@/@@@@@@@@@@/&@@/@@@%@@@@@@@@@@/@%@@@/@@@%@@@@&@@@&%@@@@(@@&%@@@@/@@@@@@@%@@@@@@@@@@@@%@@@@@@@@@@@@@@@@@@@@@@(@%@@@@@@@@@%@@@@@@&@&@@@@@@@@%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@([emailย protected]@@@@@@@@@@....%...@@@@@@@[emailย protected]@@@@@[emailย protected]@@@@@@@(..%[emailย protected]@@@@@@@@@@[emailย protected]@@@@@@@@[emailย protected]@@@,@@[emailย protected]@@@@@@@..,....@@@@@@@@@@@[emailย protected](.[emailย protected]&@@@@@@....@....([emailย protected]@@,@([emailย protected]@.(.%@@@@@@@@%,,,,,,@@@@@@@@@@@,,,,@@@@,,,@@@@@@@,,,,,,,,,,,@@@%,,..,.,,,@@&@@@@@@@@%@@@@@@@@(/(&@@@@@/@&&@@@@@@@@&/,,,,,,@@@@@@@@@(@(/&@/@@@@@%@@@@@@@@&%@@@@@@@@@@%@&@@@@@@%/@/(@&@%/(@@@@@@@/@@@@@/@@%@@@@@@%@(@@%@@@@@@@%@@/@/@@@@@@%/(/@@@/@%@/@@/&@/@@&@@@@@@@@@@@@@@@@@@@@@@@@@/@%@@@@@@/@@@@@@@@@@@@/(%@@@@@/,@%/@@@@@%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%@@@@@@@@@@/@%@@@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%&%%%%&&&&&&%%&&&&&&&&&&&&%&&&&&&&&%&&&&&&%&%&&&&&&&&&&&&&&&%&&&%%%&%%%%%%%%%%%%%%%%%%&%%%%&&%&%@@&@@%&&&&&&&&&&%%%%%%%%&%%&&&&&&&&&&&&&&%%%%%%&&%%%%%%%%%%%%%%%%%%%%%%%@@@% &@@@@@ @@@@ .&&%%%&&%%%%%&&%&&&%&%%&%%&%%%%&%%&%%%%%%%%%%%%%%%%%%, @@@/ @@@@@ @@@ @. @&&%%&%&%%%&%%%%%%%%%%&&%%%%%%%%%%%%%%%%%& &@@. [emailย protected]@@@[emailย protected]@@@@. [emailย protected] @@. @@@.&&%%&%%&&%&&&&&&&%%%%%%%%%%%%%%%%%@@@&.(@@[emailย protected]@@@@[emailย protected]@@@,........ [emailย protected] [emailย protected]@@. %%&&%&%%&&&&&&%%%%%%%%%%%%&%%%& ,@@@@@@[emailย protected]@@@@(...@@@@@[emailย protected] &@@@ (%&&&%&%%%%%%%%%%%%%%%%%%%%&. [emailย protected]@@@@@....,@@@@@@...@@@@@@@.......,. @@@@ @@%%%%%%%%%%%%%%%%%%%%%%%@@,[emailย protected]@@%%%%&%%%&%%%%&%%%%@&@@@@@@@@([emailย protected]@@. @@&%%%%%%%%%%%%&&&&&%%%%@@@,[emailย protected]&%%%&%%%%%%%%%%%%%%%%%%%%@@@@@@@@&[emailย protected]@@ @@& %%%%%%%%%%%%%%%%%%%@@@@,..,%&%%%%&%%%%%&%&%%&%%&%%%%&%%&%@@@@@@@....%@@,. @@& &%%%%%%%%%&&%%%%%%%&@@@@[emailย protected]&%%%%%%&%&%%&%%%&%%%%%%%%&%%%%%&@@@@@..@@...,@@ @%%%%%%%%%&%&%%%%%%%@@@@[emailย protected]&%&%&%&&%%&%&%%%%%@%&%%%%%%%%%&&@@@@[emailย protected][emailย protected]@ @@@%%%%%%%%%%%%%%%%%%%@@@,....%&%&%/ %%%,,,,,,,/,&%&%%%%&%%%%%@@@@[emailย protected][emailย protected] @@@ @%%%%%%%%%%%%%%%%%%%%@(......&&%&/,,,, ( ,,,,((,%%%%&&%%%%&%(@@@&[emailย protected]@@ @@%%%%%%%%%%%%%%%%%%%%%%([emailย protected]&&%,,,,,,(&&/,/ %&(@%%&&%%%%%@@@@[emailย protected]@ @@@%%%%%%%&&%%%%%%%%%%%%%%,..,@%(,,,,,@@@@./ %,./%%%%%%%%%%%@@@...(@@ @@,%%%%%%%//%%%%%%%%%%%%%( .(,,,,,(%(@@/,&,@&&%%&&%%%%%&[emailย protected]@@..(@@ /@. @%%%%%%%&%%%%%%.%@%,,,,,,,,,/,,&&&&&%&%&&%%%%%%.,@@@.,@% &@ @%%%%%%%&,, ,,,,,,,,&/.&&%/,&%%/%%&&&&%&&%&%&(..%@@,[emailย protected], /%%%%%%%%%/%/(,,,,,,,,,,,,,,,/,% .&@@[emailย protected]@@@@@@@@@@&[emailย protected]@/[emailย protected] %%%%%%%%%%%/%%%,,,%.&&/,,,,,, %%%&@@.@@/...,@@@..%@& .%%%%%%%%%%%%%((/(/,,,,,, (&&,,,,,/ .&. %@%@& .&%%%%%%&@. [emailย protected]@@. %%%%%%%%%%%%%%%%%([emailย protected]&,,,,,,,,%..,/%@. . ,[emailย protected]%%/&%%%%%%%%%%%%%&(&/&&&/%/@%.,,.&,, (,,,/@@,//%/(%/&%%%%%%&%//////@.%&@/,,.%,,,,,%,//,(/(/&/(./,,,,/@&,,,,,(((/&& ,,,,,,//(/,,&///(((((( &,,/& %@ @,,&((((((//((((/%(/&&/%@@%@ %,/((((/(((((((//(,,,,,&%//%/((/(((//((((((((((/(////((///((
interface IGnarCoin { function burn(address _from, uint256 _amount) external; function updateReward(address _from, address _to) external; }
10,821,830
pragma solidity >=0.5.0 <0.7.0; import "./Creator.sol"; import "./UserAccount.sol"; import "../cryptography/ECDSA.sol"; contract UserAccountFactory is Creator { constructor() public { } function create(uint256 _salt) external returns(address) { // return newUserAccount(_salt, msg.sender); } function createSigned(uint256 _salt, bytes calldata _signature) external returns(address) { // return newUserAccount(_salt, ECDSA.recover(keccak256(abi.encodePacked(address(this), _salt, msg.sender)), _signature)); } function predictUserAddress(uint256 _salt, address _owner) external view returns(address) { // return _computeContractAddress(abi.encodePacked(type(UserAccount).creationCode, _owner, address(0), address(0)), bytes32(keccak256(abi.encodePacked(_owner, _salt)))); } function newUserAccount(uint256 _salt, address _owner) internal returns(address) { //return _create2(0, abi.encodePacked(type(UserAccount).creationCode, _owner, address(0), address(0)), bytes32(keccak256(abi.encodePacked(_owner, _salt)))); } }
return _create2(0, abi.encodePacked(type(UserAccount).creationCode, _owner, address(0), address(0)), bytes32(keccak256(abi.encodePacked(_owner, _salt))));
function newUserAccount(uint256 _salt, address _owner) internal returns(address) { }
13,077,350
// SPDX-License-Identifier: MIT // File: contracts/NormieLib.sol pragma solidity ^0.8.9; // @author TheNormiesNFT (https://twitter.com/thenormiesnft) library NormieLib { struct Normie { uint32 skinType; // Max number is 4,294,967,296 uint32 hair; uint32 eyes; uint32 mouth; uint32 torso; uint32 pants; uint32 shoes; uint32 accessoryOne; uint32 accessoryTwo; uint32 accessoryThree; } struct Trait { string traitName; string traitType; string hash; uint16 pixelCount; uint32 traitID; } string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /* * @dev Function taken from Brecht Devos - <[email protected]> */ function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } /* * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "a"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function parseInt(string memory _a) internal pure returns (uint8 _parsedInt) { bytes memory bresult = bytes(_a); uint8 mint = 0; for (uint8 i = 0; i < bresult.length; i++) { if ( (uint8(uint8(bresult[i])) >= 48) && (uint8(uint8(bresult[i])) <= 57) ) { mint *= 10; mint += uint8(bresult[i]) - 48; } } return mint; } /* * @dev Returns a substring from [startIndex, endIndex) */ function substring(string memory str, uint256 startIndex, uint256 endIndex) internal pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } } // File: contracts/NormieTraits.sol pragma solidity ^0.8.9; // @author TheNormiesNFT (https://twitter.com/thenormiesnft) contract NormieTraits { using NormieLib for uint8; // Private variables address private owner; uint256 private SEED_NONCE = 0; mapping(address => bool) private adminAccess; NormieLib.Trait private emptyTrait = NormieLib.Trait("Empty", "Empty", "", 0, 1000001); // Public variables string public colorString = ".c000{fill:#503e38}.c001{fill:#228b22}.c002{fill:#562c1a}.c003{fill:#313131}.c004{fill:#fee761}.c005{fill:#ff0044}" ".c006{fill:#ffffff}.c007{fill:#01badb}.c008{fill:#b9f2ff}.c009{fill:#000000}.c00A{fill:#01f8fc}.c00B{fill:#0088fc}.c00C{fill:#039112}.c00D{fill:#1a3276}" ".c00E{fill:#e2646d}.c00F{fill:#ea8c8f}.c00G{fill:#f6757a}.c00H{fill:#7234b2}.c00I{fill:#b881ef}.c00J{fill:#b90e0a}.c00K{fill:#e43b44}.c00L{fill:#f5999e}" ".c00M{fill:#1258d3}.c00N{fill:#733e39}.c00O{fill:#2dcf51}.c00P{fill:#260701}.c00Q{fill:#743d2b}.c00R{fill:#dcbeb5}.c00S{fill:#e8b796}.c00T{fill:#67371a}" ".c00U{fill:#874f2e}.c00V{fill:#182812}.c00W{fill:#115c35}.c00X{fill:#ff9493}.c00Y{fill:#a22633}.c00Z{fill:#302f2f}.c010{fill:#f0d991}.c011{fill:#f2e7c7}" ".c012{fill:#0099db}.c013{fill:#2ce8f5}.c014{fill:#124e89}.c015{fill:#b86f50}.c016{fill:#777777}.c017{fill:#afafaf}.c018{fill:#878787}.c019{fill:#ffed1b}" ".c01A{fill:#1b1a1b}.c01B{fill:#131314}.c01C{fill:#191970}.c01D{fill:#bb8b1f}.c01E{fill:#f8f7ed}.c01F{fill:#072083}.c01G{fill:#f65c1a}.c01H{fill:#4b5320}" ".c01I{fill:#8a9294}.c01J{fill:#969cba}.c01K{fill:#c0c0c0}.c01L{fill:#8c92ac}.c01M{fill:#01796f}.c01N{fill:#ce1141}.c01O{fill:#ff007f}.c01P{fill:#b6005b}" ".c01Q{fill:#feed26}.c01R{fill:#dccd21}.c01S{fill:#080808}.c01T{fill:#b2ffff}.c01U{fill:#18a8d8}.c01V{fill:#818589}.c01W{fill:#98fb98}.c01X{fill:#e0c4ff}" ".c01Y{fill:#e1c4ff}.c01Z{fill:#c0a8da}.c020{fill:#ce2029}.c021{fill:#b01b23}.c022{fill:#87ceeb}.c023{fill:#ff0000}"; uint32 public CURRENT_TRAIT = 1; // Storage of all previous collections mapping(uint256 => uint256[]) public currentCollectionTraits; mapping(uint256 => NormieLib.Trait) public traitIDToTrait; string[] LETTERS = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; // Array of the current trait rarity available in the current collection with 10 traits total uint256[][10] public traitRarity; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "Not the owner"); _; } /** * @dev Throws if called by an account that does not have adminAccess. */ modifier onlyAdmin() { require(adminAccess[msg.sender], "No admin access"); _; } constructor() { owner = msg.sender; // Register the Empty trait. traitIDToTrait[1000001] = emptyTrait; traitRarity[0] = [2500, 5000, 7500, 10000]; traitRarity[1] = [400, 800, 1600, 2400, 3200, 4200, 5200, 6600, 8000, 10000]; traitRarity[2] = [800, 1600, 2800, 4000, 5500, 7000, 8500, 10000]; traitRarity[3] = [200, 400, 1300, 2200, 4150, 6100, 8050, 10000]; traitRarity[4] = [200, 800, 1400, 2000, 3000, 4000, 5000, 6600, 8200, 10000]; traitRarity[5] = [200, 600, 1600, 2800, 4000, 6000, 8000, 10000]; traitRarity[6] = [100, 600, 1100, 2600, 4100, 7050, 10000]; traitRarity[7] = [100,600,1100,2100,10000]; traitRarity[8] = [100,800,2400,4400,10000]; traitRarity[9] = [100,600,2100,10000]; } ///////////////////////////// ONLY ADMIN FUNCTIONS ///////////////////////////// /** * @dev Function used to generate a Normie. * @param tokenID The token ID of the new Normie. * @param _address The address that will own the Normie. Used in hashing function. * @return Edited normie. Used by mintNormie function in Normies.sol. */ function generateNormie(uint256 tokenID, address _address) external onlyAdmin returns (NormieLib.Normie memory) { for (uint256 i=0; i < 10; i++){ require(traitRarity[i].length == currentCollectionTraits[i].length, "Trait arrays mismatch"); } uint256[] memory generatedHash = hash(tokenID, _address); return NormieLib.Normie( uint32(currentCollectionTraits[0][generatedHash[0]]), uint32(currentCollectionTraits[1][generatedHash[1]]), uint32(currentCollectionTraits[2][generatedHash[2]]), uint32(currentCollectionTraits[3][generatedHash[3]]), uint32(currentCollectionTraits[4][generatedHash[4]]), uint32(currentCollectionTraits[5][generatedHash[5]]), uint32(currentCollectionTraits[6][generatedHash[6]]), uint32(currentCollectionTraits[7][generatedHash[7]]), uint32(currentCollectionTraits[8][generatedHash[8]]), uint32(currentCollectionTraits[9][generatedHash[9]]) ); } /* * @dev Generates a array of length 10 that contains what indexes to use for each trait. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @return An array of size 10 with integers representing the trait within the current collection to use. */ function hash(uint256 _t, address _a) public onlyAdmin returns (uint256[] memory) { // This will generate a 10 trait array. All values in the array are random. uint256[] memory ret = new uint[](10); uint counter = SEED_NONCE; uint256 _randinput = 0; uint256 left = 0; uint256 right = 0; uint256 mid = 0; uint256 traitRarityValue = 0; for (uint256 i = 0; i <= 9; i++) { counter++; _randinput = uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, counter ) ) ) % 10000; left = 0; right = traitRarity[i].length - 1; // Binary search for the index while (left < right){ mid = (left + right) / 2; traitRarityValue = traitRarity[i][mid]; if (traitRarityValue == _randinput){ left = mid; break; } else if (traitRarityValue < _randinput){ left = mid + 1; } else { right = mid; } } ret[i] = left; } SEED_NONCE = counter; return ret; } ///////////////////////////// PUBLIC READ FUNCTIONS ///////////////////////////// /* * @dev Hash to SVG function for a normie. * @param normie The Normie that we are getting the URI of. * @param normieID the ID of the normie. * @return URI of a Normie as a string. */ function getNormieURI(NormieLib.Normie memory normie, uint256 normieID) external view returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", NormieLib.encode( bytes(string(abi.encodePacked( '{"name": "Normie #', NormieLib.toString(normieID), '", "description": "Normies are generated and stored 100% on the blockchain.", "image": "data:image/svg+xml;base64,', NormieLib.encode( bytes(normieToSVG(normie)) ), '","attributes":', getMainTraitsString(normie), getOptionalTraitsString(normie), "}"))) ))); } /* * @dev Returns Asset URI for a given trait. * @param assetID The ID of the asset we are getting the URI of. * @return URI of an asset as a string. */ function getAssetURI(uint256 assetID) external view returns (string memory) { NormieLib.Trait memory trait = traitIDToTrait[assetID]; return string( abi.encodePacked( "data:application/json;base64,", NormieLib.encode( bytes( string( abi.encodePacked( '{"name": "', trait.traitName, '", "description": "Normie assets are generated and stored 100% on the blockchain.", "image": "data:image/svg+xml;base64,', NormieLib.encode( bytes(assetToSVG(assetID)) ), '","attributes":', getSingleTraitString(trait), "}" ) ) ) ) ) ); } /** * @dev Gets a trait by its ID number using the provided "traitID" and returns its trait type. Used in Normies.sol * @param traitID The traitID to get from the traitIDToTrait mapping. * @return string object. */ function getTraitTypeByTraitID(uint256 traitID) external view returns (string memory){ return traitIDToTrait[traitID].traitType; } /** * @dev Gets a trait from the current collection using the provided "traitIndex" and "index". * Used in minting function. * @param traitIndex The index which indicates what type of trait it is [0-9]. * @param index The index of the specific trait to grab. Variable array size depending on collection. * @return Trait object. */ function getTraitFromCurrentCollection(uint256 traitIndex, uint256 index) public view returns (NormieLib.Trait memory) { return traitIDToTrait[currentCollectionTraits[traitIndex][index]]; } ///////////////////////////// PRIVATE READ FUNCTIONS ///////////////////////////// /* * @notice Adapted function from Anonymice contract * @dev Hash to SVG function for normie. * @param normie The Normie object to generate an SVG image for. * @return Normie SVG as a string. */ function normieToSVG(NormieLib.Normie memory normie) private view returns (string memory) { string memory svgString; for (uint8 i = 0; i <= 9; i++) { NormieLib.Trait memory trait = getNormieTraitObject(normie, i); for (uint16 j = 0; j < trait.pixelCount; j++) { string memory thisPixel = NormieLib.substring(trait.hash, j * 5, j * 5 + 5); uint8 x = letterToNumber(NormieLib.substring(thisPixel, 0, 1)); uint8 y = letterToNumber(NormieLib.substring(thisPixel, 1, 2)); svgString = string( abi.encodePacked( svgString, "<rect class='c", NormieLib.substring(thisPixel, 2, 5), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); } } svgString = string( abi.encodePacked( '<svg id="normie-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #normie-svg{shape-rendering: crispedges;} ", colorString, "</style></svg>" ) ); return svgString; } /* * @notice Adapted function from Anonymice contract * @dev Hash to SVG function for a trait. * @param assetID The assetID for the trait we want to create an SVG for. * @return Asset SVG as a string. */ function assetToSVG(uint256 assetID) private view returns (string memory) { NormieLib.Trait memory trait = traitIDToTrait[assetID]; string memory svgString; for (uint16 j = 0; j < trait.pixelCount; j++) { string memory thisPixel = NormieLib.substring(trait.hash, j * 5, j * 5 + 5); uint8 x = letterToNumber(NormieLib.substring(thisPixel, 0, 1)); uint8 y = letterToNumber(NormieLib.substring(thisPixel, 1, 2)); svgString = string( abi.encodePacked( svgString, "<rect class='c", NormieLib.substring(thisPixel, 2, 5), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); } svgString = string( abi.encodePacked( '<svg id="normie-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #normie-svg{shape-rendering: crispedges;} ", colorString, "</style></svg>" ) ); return svgString; } /* * @notice Original author is Anonymice. * @dev Helper function to reduce pixel size within contract. * @param _inputLetter The letter to change from base26 to base10. * @return A base 10 number. */ function letterToNumber(string memory _inputLetter) private view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /* * @dev Gets the trait for a given "normie" using the provided "traitIndex". * @param normie The normie whose trait we want to get. * @param traitIndex Index that determines which trait to return [0-9]. * @return Trait object. */ function getNormieTraitObject(NormieLib.Normie memory normie, uint256 traitIndex) private view returns (NormieLib.Trait memory) { if (traitIndex == 0) { return traitIDToTrait[normie.skinType]; } else if (traitIndex == 1) { return traitIDToTrait[normie.pants]; } else if (traitIndex == 2){ return traitIDToTrait[normie.shoes]; } else if (traitIndex == 3) { return traitIDToTrait[normie.torso]; } else if (traitIndex == 4) { return traitIDToTrait[normie.mouth]; } else if (traitIndex == 5) { return traitIDToTrait[normie.eyes]; } else if (traitIndex == 6) { return traitIDToTrait[normie.hair]; } else if (traitIndex == 7) { return traitIDToTrait[normie.accessoryOne]; } else if (traitIndex == 8) { return traitIDToTrait[normie.accessoryTwo]; } else { return traitIDToTrait[normie.accessoryThree]; } } /* * @dev Generates the string metadata for base Normie traits. * @param normie The normie object to generate URI string from. * @return Metadata for the normie as a string. Used for any call to URI.. */ function getMainTraitsString(NormieLib.Normie memory normie) private view returns (string memory) { return string(abi.encodePacked( '{"Skin Type":"', traitIDToTrait[normie.skinType].traitName, '","Hair":"', traitIDToTrait[normie.hair].traitName, '","Eyes":"', traitIDToTrait[normie.eyes].traitName, '","Mouth":"', traitIDToTrait[normie.mouth].traitName, '","Torso":"', traitIDToTrait[normie.torso].traitName, '","Pants":"', traitIDToTrait[normie.pants].traitName, '","Shoes":"', traitIDToTrait[normie.shoes].traitName ) ); } /* * @dev Generates the string metadata for optional Normie traits. * @param normie The normie object to generate URI string from. * @return Metadata for the normie as a string. Used for any call to URI. */ function getOptionalTraitsString(NormieLib.Normie memory normie) private view returns (string memory) { return string(abi.encodePacked( '","Accessory One":"', traitIDToTrait[normie.accessoryOne].traitName, '","Accessory Two":"', traitIDToTrait[normie.accessoryTwo].traitName, '","Accessory Three":"', traitIDToTrait[normie.accessoryThree].traitName, '"}' ) ); } /** * @dev Generates the string metadata for a single trait NFT. * @param trait The trait object to generate URI string from. * @return Metadata for the asset as a string. Used for any call to URI. */ function getSingleTraitString(NormieLib.Trait memory trait) private pure returns (string memory) { return string(abi.encodePacked( '{"Trait Type":"', trait.traitType, '","Trait Name":"', trait.traitName, '"}' ) ); } ///////////////////////////// OWNER FUNCTIONS ///////////////////////////// //-------------------------- // Trait Rarity functions //-------------------------- /** * @dev Clears the trait rarity for a given trait (Ex. hair which is 0). * @param traitIndex The index we want to clear. */ function clearTraitRarity(uint256 traitIndex) external onlyOwner { delete traitRarity[traitIndex]; } /** * @dev Clears all trait rarities. */ function clearAllTraitRarities() external onlyOwner { for (uint256 i = 0; i < traitRarity.length; i++){ delete traitRarity[i]; } } /** * @dev Adds an array of trait rarity values to the traix index. Contains safety check to ensure the array sums to 10,000. Also checks to make sure trait rarity is empty to begin with. * @param traitIndex The trait index to add trait rarities to. * @param newRarities Integer array of rarities that should sum to 10,000. */ function addTraitRarity(uint256 traitIndex, uint256[] memory newRarities) external onlyOwner { require(traitRarity[traitIndex].length == 0, "Not empty trait"); require(newRarities[newRarities.length-1] == 10000, "Trait rarity does not end in 10,000. Reverting"); for (uint256 i = 0; i < newRarities.length; i++) { traitRarity[traitIndex].push(newRarities[i]); } return; } //-------------------------- // Collection functions //-------------------------- /** * @dev Clears the traits for a given trait index in the current collection (Ex. hair which is 0). * @param index The index to clear current collection traits from. */ function clearCurrentCollectionTrait(uint256 index) external onlyOwner { delete currentCollectionTraits[index]; } /** * @dev Clears all traits for the current collection. */ function clearAllTraitsInCurrentCollection() external onlyOwner { for (uint256 i = 0; i < 10; i++){ delete currentCollectionTraits[i]; } } /** * Adds new trait to trait map. Good to use when adding new traits for giveaways or one offs. * @param newTraits Array of traits to add to trait map. */ function addTraitToTraitMap(NormieLib.Trait[] memory newTraits) external onlyOwner { uint32 currentTraitLocal = CURRENT_TRAIT; for (uint256 i = 0; i < newTraits.length; i++){ NormieLib.Trait memory _trait = NormieLib.Trait( newTraits[i].traitName, newTraits[i].traitType, newTraits[i].hash, newTraits[i].pixelCount, 1000001 + currentTraitLocal ); traitIDToTrait[1000001 + currentTraitLocal] = _trait; currentTraitLocal = currentTraitLocal + 1; } CURRENT_TRAIT = currentTraitLocal; } /** * @dev Function used to edit a trait in place in case we hashed incorrectly or something. * @param traitID Trait ID of the trait we want to edit * @param newTraitData Struct containing data that we want to overwrite the current trait with. */ function editTrait(uint256 traitID, NormieLib.Trait memory newTraitData) external onlyOwner { NormieLib.Trait memory _trait = traitIDToTrait[traitID]; _trait.traitName = newTraitData.traitName; _trait.traitType = newTraitData.traitType; _trait.hash = newTraitData.hash; _trait.pixelCount = newTraitData.pixelCount; traitIDToTrait[traitID] = _trait; } /** * @dev Emergency function to remove incorrect traits from existence. Checks to make sure ID provided is greater than 1,000,000. * @param traitID The trait to remove from existence. */ function removeTraitFromTraitMap(uint256 traitID) external onlyOwner { require(traitID >= 1000000, "Trait ID < 1,000,000"); traitIDToTrait[traitID] = emptyTrait; } /** * @dev Adds traits to specific location. Good to use for reusing assets in another collection. (Ex. Reusing skinType assets). * @param traitIndex The index to add these traits to. * @param traitID Array of integers representing the traits to add to the given collectionNumber and traitIndex. */ function addTraitsToCurrentCollection(uint256 traitIndex, uint256[] memory traitID) external onlyOwner { require(currentCollectionTraits[traitIndex].length + traitID.length <= traitRarity[traitIndex].length, "Trait array mismatch"); for (uint256 i = 0; i < traitID.length; i++){ currentCollectionTraits[traitIndex].push(traitID[i]); } } /** * @dev Sets the current color string. Allows us to add new colors in the future * @param _colorString The new color string. */ function setColorString(string calldata _colorString) external onlyOwner { colorString = _colorString; } /** * @dev Used to add admin acccess for a contract * @param _addressToAdd The address to give admin access to. */ function addAdminAccess(address _addressToAdd) external onlyOwner { adminAccess[_addressToAdd] = true; } }
Adds traits to specific location. Good to use for reusing assets in another collection. (Ex. Reusing skinType assets). traitIndex The index to add these traits to. traitID Array of integers representing the traits to add to the given collectionNumber and traitIndex./
function addTraitsToCurrentCollection(uint256 traitIndex, uint256[] memory traitID) external onlyOwner { require(currentCollectionTraits[traitIndex].length + traitID.length <= traitRarity[traitIndex].length, "Trait array mismatch"); for (uint256 i = 0; i < traitID.length; i++){ currentCollectionTraits[traitIndex].push(traitID[i]); } }
12,603,913
./full_match/43114/0x096F07be24Fb85528bf67f2790a3B72F764D4540/sources/artifacts/MasterChef.sol
1/x Test reciprocal(0) fails Test reciprocal(fixed1()) returns fixed1()/
function reciprocal(int256 x) internal pure returns (int256) { assert(x != 0); }
4,572,081
pragma solidity ^0.4.18; import './DDNSBanking.sol'; import './common/SafeMath.sol'; import './common/Destructible.sol'; contract DDNSCore is DDNSBanking, Destructible { using SafeMath for uint256; event LogNewDomain( bytes32 domainName, bytes32 ipAddress, address indexed domainOwner, bytes12 topLevelDomain ); event LogRegistrationRenewed( bytes32 indexed domainName, bytes32 ipAddress, uint256 validUntil, address indexed domainOwner, bytes12 topLevelDomain ); event LogEditedDomain( bytes32 indexed domainName, bytes12 topLevelDomain, bytes32 newIpAddress ); event LogOwnershipTransfer( bytes32 domainName, bytes12 topLevelDomain, address indexed from, address indexed to ); event LogReceipt( address indexed receiver, bytes32 domainName, uint256 amountPaid, uint256 timeBought ); struct DomainDetails { bytes32 domainName; bytes32 ipAddress; uint256 validUntil; address domainOwner; bytes12 topLevelDomain; } struct Receipt { bytes32 domainName; uint256 amountPaid; uint256 timeBought; } bytes1 public constant BYTES_DEFAULT_VALUE = bytes1(0x00); uint8 public constant DOMAIN_NAME_MIN_LENGTH = 5; uint8 public constant IP_ADDRESS_MIN_LENGTH = 6; uint8 public constant TOP_LEVEL_DOMAIN_MIN_LENGTH = 1; uint8 public constant PRICE_INCREASE_BOUND_INDEX = 9; mapping(bytes32 => DomainDetails) public domains; mapping(address => Receipt[]) public receipts; modifier nameLengthRestricted(bytes32 _domainName) { require(_domainName[DOMAIN_NAME_MIN_LENGTH] != BYTES_DEFAULT_VALUE); _; } modifier ipAddressLengthRestricted(bytes32 _ipAddress) { require(_ipAddress[IP_ADDRESS_MIN_LENGTH] != BYTES_DEFAULT_VALUE); _; } modifier topLevelDomainLengthRestricted(bytes12 _topLevelDomain) { require(_topLevelDomain[TOP_LEVEL_DOMAIN_MIN_LENGTH] != BYTES_DEFAULT_VALUE); _; } modifier nameLengthPriced(bytes32 _domainName) { require(msg.value >= _adjustPriceToNameLength(_domainName)); _; } modifier onlyDomainOwner(bytes32 _domainName, bytes12 _topLevelDomain) { bytes32 key = getDomainKey(_domainName, _topLevelDomain); require(domains[key].domainOwner == msg.sender); _; } function registerDomain( bytes32 _domainName, bytes32 _ipAddress, bytes12 _topLevelDomain ) public payable nameLengthRestricted(_domainName) ipAddressLengthRestricted(_ipAddress) topLevelDomainLengthRestricted(_topLevelDomain) nameLengthPriced(_domainName) { bytes32 key = getDomainKey(_domainName, _topLevelDomain); /* solium-disable-next-line security/no-block-members */ require(domains[key].validUntil < now); if (_isNewDomainRegistration(key)) { LogNewDomain(_domainName, _ipAddress, msg.sender, _topLevelDomain); } /* solium-disable-next-line security/no-block-members */ domains[key] = DomainDetails(_domainName, _ipAddress, now.add(expiryPeriod), msg.sender, _topLevelDomain); _issueReceipt(_domainName); } function renewDomainRegistration(bytes32 _domainName, bytes12 _topLevelDomain) public payable nameLengthPriced(_domainName) onlyDomainOwner(_domainName, _topLevelDomain) { bytes32 key = getDomainKey(_domainName, _topLevelDomain); /* solium-disable-next-line security/no-block-members */ if (domains[key].validUntil > now) { domains[key].validUntil = domains[key].validUntil.add(expiryPeriod); } else { /* solium-disable-next-line security/no-block-members */ domains[key].validUntil = now.add(expiryPeriod); } LogRegistrationRenewed( _domainName, domains[key].ipAddress, domains[key].validUntil, domains[key].domainOwner, domains[key].topLevelDomain ); _issueReceipt(_domainName); } function editDomainIp(bytes32 _domainName, bytes12 _topLevelDomain, bytes32 _newIpAddress) public onlyDomainOwner(_domainName, _topLevelDomain) ipAddressLengthRestricted(_newIpAddress) { bytes32 key = getDomainKey(_domainName, _topLevelDomain); domains[key].ipAddress = _newIpAddress; LogEditedDomain(_domainName, _topLevelDomain, _newIpAddress); } function transferOwnership(bytes32 _domainName, bytes12 _topLevelDomain, address _to) public onlyDomainOwner(_domainName, _topLevelDomain) { require(_to != address(0)); bytes32 key = getDomainKey(_domainName, _topLevelDomain); domains[key].domainOwner = _to; LogOwnershipTransfer(_domainName, _topLevelDomain, msg.sender, _to); } function getDomainPrice(bytes32 _domainName) public view returns (uint256) { return _adjustPriceToNameLength(_domainName); } function getDomainKey(bytes32 _domainName, bytes12 _topLevelDomain) public pure returns (bytes32) { return keccak256(_domainName, _topLevelDomain); } function _adjustPriceToNameLength(bytes32 _domainName) private view returns (uint256) { if (_domainName[PRICE_INCREASE_BOUND_INDEX] == BYTES_DEFAULT_VALUE) { uint8 multiplier = 1; while (_domainName[PRICE_INCREASE_BOUND_INDEX - multiplier] == BYTES_DEFAULT_VALUE) { multiplier++; } uint256 additionalTax = registrationCost.mul(multiplier * 10); additionalTax = additionalTax.div(100); return registrationCost.add(additionalTax); } return registrationCost; } function _isNewDomainRegistration(bytes32 _key) private view returns(bool) { return domains[_key].validUntil == 0; } function _issueReceipt(bytes32 _domainName) private { /* solium-disable-next-line security/no-block-members */ receipts[msg.sender].push(Receipt(_domainName, msg.value, now)); /* solium-disable-next-line security/no-block-members */ LogReceipt(msg.sender, _domainName, msg.value, now); } }
solium-disable-next-line security/no-block-members /
function registerDomain( bytes32 _domainName, bytes32 _ipAddress, bytes12 _topLevelDomain ) public payable nameLengthRestricted(_domainName) ipAddressLengthRestricted(_ipAddress) topLevelDomainLengthRestricted(_topLevelDomain) nameLengthPriced(_domainName) { bytes32 key = getDomainKey(_domainName, _topLevelDomain); require(domains[key].validUntil < now); if (_isNewDomainRegistration(key)) { LogNewDomain(_domainName, _ipAddress, msg.sender, _topLevelDomain); } _issueReceipt(_domainName); }
979,883
./full_match/1/0x0000000304aAD016bA7a745da3cE64f6198B76B3/sources/lib/solady/src/utils/FixedPointMathLib.sol
Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) { assembly { z := sdiv(x, y) } }
3,200,589
pragma solidity ^0.4.19; import "./crowdsale/PreSaleCrowdsale.sol"; import "./math/SafeMath.sol"; import "./OneSmartToken.sol"; /** * In 2018 and in real world a huge amount of conditions required to success processing * private round investments. * * We do not want to * 1. Do any kind of non blockchain related investors cabinets * 2. Do any kind of manual operations for wei/ONE token distribution like manual * charge or refund or something like this * 3. Promise "honestly" to not spend team/advisers or any kind of other tokens. All * limitations for all members should be in smart contract. * 4. Be unclear for banks. KYC compliance should be integrated to smart contract. */ contract OneCrowdsale is PreSaleCrowdsale { using SafeMath for uint256; OneSmartToken public ONE = new OneSmartToken(this); // ONE to ETH base rate uint256 public constant EXCHANGE_RATE = 500; // Minimal length of invoice id for fiat/BTC payments uint256 public constant MIN_INVOICE_LENGTH = 5; struct DealDeposit{ address refundWallet; uint256 depositedETH; uint256 depositedTokens; uint256 transferred; } struct DepositTimeLock { uint256 mainCliffAmount; uint256 mainCliffTime; uint256 additionalCliffTime; uint256 additionalCliffAmount; } /***********************************************************************/ /** Events /***********************************************************************/ event DepositAdded( address indexed wallet, address indexed refundWallet, uint256 value, uint256 amount ); event DepositTimeLockAssigned( address indexed _wallet, uint256 _mainCliffAmount, uint256 _mainCliffTime, uint256 _additionalCliffAmount, uint256 _additionalCliffTime ); event DepositTimeLockDeleted(address indexed _wallet); event RefundedDeposit(address indexed beneficiary, uint256 value, uint256 amount); event TokenClaimed(address indexed _wallet, uint256 value); /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param bonusBeneficiary who got the bonus tokens * @param value weis paid for purchase * @param amount amount of tokens purchased * @param bonusAmount amount of bonus tokens purchased */ event TokenPurchased( address indexed purchaser, address indexed beneficiary, address indexed bonusBeneficiary, uint256 value, uint256 amount, uint256 bonusAmount ); event CrowdsakeFinished(); event TokenLocked(); event TokenUnlocked(); event AdditionalCliffTimeGreaterThanZero(); event NotTransferETHToRefund(); /***********************************************************************/ /** Members /***********************************************************************/ bool public isFinalized = false; uint256 finalizedTime = 0; uint256 constant reservePart = 17; // 17% of the total supply for future strategic plans for the created ecosystem uint256 constant teamPart = 12; // 12% of the total supply for the team and SDK developers uint256 constant operatingPart = 8; // 8% of the total supply for Protocol One crowdsale campaign uint256 constant advisersPart = 3; // 3% of the total supply for professional fees and Bounties uint256 constant bountyPart = 1; // 1% of the total supply for bounty program uint256 constant icoPart = 59; // 59% of total supply for public and private offers address public wallet; // Address where funds are collected address public walletTeam; address public walletAdvisers; address public walletOperating; address public walletReserve; address public walletBounty; mapping(address => DealDeposit) public depositMap; mapping(address => DepositTimeLock) public depositTimeLockMap; /** * @param _hardCap Max amount of wei to be contributed */ constructor( address _wallet, address _walletTeam, address _walletAdvisers, address _walletOperating, address _walletReserve, address _walletBounty, uint256 _openingTime, uint256 _closingTime, uint256 _softCap, uint256 _hardCap ) public Crowdsale(_openingTime, _closingTime, EXCHANGE_RATE, _softCap, _hardCap) { require(_wallet != address(0)); require(_walletTeam != address(0)); require(_walletAdvisers != address(0)); require(_walletOperating != address(0)); require(_walletReserve != address(0)); require(_walletBounty != address(0)); wallet = _wallet; walletTeam = _walletTeam; walletAdvisers = _walletAdvisers; walletOperating = _walletOperating; walletReserve = _walletReserve; walletBounty = _walletBounty; } /***********************************************************************/ /** Public Methods /***********************************************************************/ /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { if (msg.sender != wallet ) { buyTokens(msg.sender); } } /** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable onlyWhitelisted onlyWhileOpen hardCapNotReached { uint256 weiAmount = msg.value; PreSaleConditions storage deal = investorsMap[_beneficiary]; require(deal.wallet != address(0)); require(deal.weiMinAmount <= weiAmount); require(deal.completed == false); require(rate > 0); // calculate token amount to be created based on fixed rate uint256 baseDealTokens = weiAmount.mul(rate); // get investor bonus rate based on current day from ICO start and personal deal rate uint256 bonusTokens = 0; uint256 bonusRate = getBonusRate(_beneficiary); if (bonusRate > 0) { uint256 totalBonusTokens = baseDealTokens.mul(bonusRate).div(100); // calculate bonus part in tokens bonusTokens = totalBonusTokens.mul(deal.bonusShare).div(100); baseDealTokens.add(totalBonusTokens.sub(bonusTokens)); } weiRaised = weiRaised.add(weiAmount); addDeposit(_beneficiary, deal.wallet, weiAmount, baseDealTokens); if (bonusTokens > 0) { addDeposit(_beneficiary, deal.bonusWallet, 0, bonusTokens); } deal.completed = true; forwardFunds(); emit TokenPurchased(_beneficiary, deal.wallet, deal.bonusWallet, weiAmount, baseDealTokens, bonusTokens); } /** * @dev Allow managers to lock tokens distribution while campaign not ended. */ function lockTokens() external onlyOwner { ONE.lock(); emit TokenLocked(); } /** * @dev Allow managers to unlock tokens distribution while campaign not ended. */ function unlockTokens() external onlyOwner { ONE.unlock(); emit TokenUnlocked(); } /** * @dev Add internal deposit record before actual token distribution. * * @param _refundWallet who paid for the tokens * @param _wallet who got the tokens * @param _wei weis paid for purchase * @param _tokens amount of tokens purchased */ function addDeposit( address _refundWallet, address _wallet, uint256 _wei, uint256 _tokens ) internal { require(_refundWallet != address(0)); require(_wallet != address(0)); require(_tokens > 0); DealDeposit storage deposit = depositMap[_wallet]; deposit.refundWallet = _refundWallet; deposit.depositedETH = deposit.depositedETH.add(_wei); deposit.depositedTokens = deposit.depositedTokens.add(_tokens); ONE.mint(address(this), _tokens.add(_tokens)); //UNDONE emit DepositAdded(_wallet, _refundWallet, _wei, _tokens); } /** * @dev Add deposit time lock for given wallet. * * @param _wallet address of wallet to got the tokens * @param _mainCliffAmount percent of token could taken before mainCliffTime * @param _mainCliffTime days from finish time for main cliff * @param _additionalCliffAmount percent of token could taken before _additionalCliffTime * @param _additionalCliffTime days from finish time for additional cliff * * * | /---------------- * | | all remaining * | | tokens * | | * | | * | | * | /--------------------- * | | + additional cliff * | | amount * | /-----------/ * | | * | | main cliff * | | amount * +===+===========+--------------------+-------------------> time * Crowdsale main cliff additional cliff * finish */ function assignDepositTimeLock( address _wallet, uint256 _mainCliffAmount, uint256 _mainCliffTime, uint256 _additionalCliffAmount, uint256 _additionalCliffTime ) external onlyAdmins onlyWhileOpen { require(_wallet != address(0)); require(_mainCliffTime > 0); require(_mainCliffAmount > 0 && _mainCliffAmount < 100); if (_additionalCliffTime > 0) { require(_additionalCliffTime > _mainCliffTime); require(_mainCliffAmount.add(_additionalCliffAmount) < 100); } else { emit AdditionalCliffTimeGreaterThanZero(); } DepositTimeLock storage timeLock = depositTimeLockMap[_wallet]; timeLock.mainCliffAmount = _mainCliffAmount; timeLock.mainCliffTime = _mainCliffTime.mul(86400); timeLock.additionalCliffAmount = _additionalCliffAmount; timeLock.additionalCliffTime = _additionalCliffTime.mul(86400); emit DepositTimeLockAssigned(_wallet, _mainCliffAmount, _mainCliffTime, _additionalCliffAmount, _additionalCliffTime); } /** * @dev Remove deposit time lock * * @param _wallet address of wallet to got the tokens */ function deleteDepositTimeLock(address _wallet) external onlyAdmins onlyWhileOpen { require(_wallet != address(0)); delete depositTimeLockMap[_wallet]; emit DepositTimeLockDeleted(_wallet); } /** * @dev Allow manager to refund deposits without kyc passed. * * @param _wallet the address of the investor wallet for ETC payments. */ function refundDeposit(address _wallet) external onlyAdmins { DealDeposit storage deposit = depositMap[_wallet]; require(deposit.depositedTokens > 0); uint256 refundTokens = deposit.depositedTokens; deposit.depositedTokens = 0; ONE.burn(address(this), refundTokens); uint256 ETHToRefund = deposit.depositedETH; if (ETHToRefund > 0) { deposit.depositedETH = 0; deposit.refundWallet.transfer(ETHToRefund); } else { emit NotTransferETHToRefund(); } emit RefundedDeposit(_wallet, ETHToRefund, refundTokens); } /** * @dev Investor should call this method to claim they tokens from deposit */ function claimTokens() public onlyKYCPassed { require(isFinalized); address investor = msg.sender; DealDeposit storage deposit = depositMap[investor]; require(deposit.depositedTokens > 0); DepositTimeLock storage timeLock = depositTimeLockMap[investor]; uint256 depositedToken = deposit.depositedTokens; uint256 vested; // First time range if (timeLock.mainCliffTime > 0 && finalizedTime.add(timeLock.mainCliffTime) >= now) { vested = depositedToken.mul(timeLock.mainCliffAmount).div(100); } else if (timeLock.additionalCliffTime > 0 && finalizedTime.add(timeLock.mainCliffTime) < now && finalizedTime.add(timeLock.additionalCliffTime) >= now) { // Second time range uint256 totalCliff = timeLock.mainCliffAmount.add(timeLock.additionalCliffAmount); vested = depositedToken.mul(totalCliff).div(100); } else { vested = depositedToken; } if (vested == 0) { return; } // Make sure the holder doesn't transfer more than what he already has. uint256 transferable = vested.sub(deposit.transferred); if (transferable == 0) { return; } deposit.transferred = deposit.transferred.add(transferable); ONE.unlock(); ONE.transfer(investor, transferable); ONE.lock(); emit TokenClaimed(investor, transferable); } /** * @param _beneficiary the address of the investor wallet to get current bonus rate. */ function getBonusRate(address _beneficiary) internal view returns (uint256) { uint256 bonusRateTime = investorsMap[_beneficiary].bonusRateTime; uint256 bonusRate = investorsMap[_beneficiary].bonusRate; if (bonusRateTime >= now && bonusRate > 0) { return bonusRate; } if (now < (openingTime.add(33 days))) {return 60;} //60% if (now < (openingTime.add(61 days))) {return 50;} //50% if (now < (openingTime.add(115 days))) {return 40;} //40% if (now < (openingTime.add(145 days))) {return 30;} //30% if (now < (openingTime.add(208 days))) {return 20;} //20% if (now < (openingTime.add(212 days))) {return 10;} //10% if (now < (openingTime.add(216 days))) {return 8;} //8% if (now < (openingTime.add(220 days))) {return 6;} //6% if (now < (openingTime.add(224 days))) {return 4;} //4% if (now < (openingTime.add(228 days))) {return 2;} //2% return 0; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finishCrowdsale() onlyOwner public { require(!isFinalized); require(hasClosed() || hardCapReached()); for (uint256 i = 0; i < invoiceMapKeys.length; i++) { address investorWallet = invoiceMapKeys[i]; uint256 tokens = invoicesMap[investorWallet]; addDeposit(investorWallet, investorWallet, 0, tokens); } uint256 newTotalSupply = ONE.totalSupply().mul(100).div(icoPart); ONE.mint(walletTeam, newTotalSupply.mul(teamPart).div(100)); ONE.mint(walletAdvisers, newTotalSupply.mul(advisersPart).div(100)); ONE.mint(walletOperating, newTotalSupply.mul(operatingPart).div(100)); ONE.mint(walletReserve, newTotalSupply.mul(reservePart).div(100)); ONE.mint(walletBounty, newTotalSupply.mul(bountyPart).div(100)); ONE.finishMinting(); finalizedTime = now; emit CrowdsakeFinished(); isFinalized = true; } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function forwardFunds() internal { wallet.transfer(msg.value); } }
Investor should call this method to claim they tokens from deposit/ First time range Second time range
function claimTokens() public onlyKYCPassed { require(isFinalized); address investor = msg.sender; DealDeposit storage deposit = depositMap[investor]; require(deposit.depositedTokens > 0); DepositTimeLock storage timeLock = depositTimeLockMap[investor]; uint256 depositedToken = deposit.depositedTokens; uint256 vested; if (timeLock.mainCliffTime > 0 && finalizedTime.add(timeLock.mainCliffTime) >= now) { vested = depositedToken.mul(timeLock.mainCliffAmount).div(100); } else if (timeLock.additionalCliffTime > 0 && finalizedTime.add(timeLock.mainCliffTime) < now && finalizedTime.add(timeLock.additionalCliffTime) >= now) { uint256 totalCliff = timeLock.mainCliffAmount.add(timeLock.additionalCliffAmount); vested = depositedToken.mul(totalCliff).div(100); vested = depositedToken; } if (vested == 0) { return; } if (transferable == 0) { return; } deposit.transferred = deposit.transferred.add(transferable); ONE.unlock(); ONE.transfer(investor, transferable); ONE.lock(); emit TokenClaimed(investor, transferable); }
12,616,562
./full_match/1/0x79480634dc632cdf68295CdEBF07E217dCB6743f/sources/ThePepeCartel.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("ThePepeCartel", "DONPEPE") { 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 = 15; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 20; uint256 _sellLiquidityFee = 20; uint256 _sellDevFee = 5; uint256 _earlySellDevFee = 0; uint256 _earlySellMarketingFee = 5; uint256 totalSupply = 420690000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellDevFee = _earlySellDevFee; earlySellMarketingFee = _earlySellMarketingFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(marketingWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingWallet, true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
3,120,526
./partial_match/5/0xDb671DD4ad1Ce8dbB403690ab5510A849dE777A9/sources/MainTokenContract.sol
This function returns the total supply or maximum supply of the ERC20 token
function totalSupply() public view virtual returns (uint256){ return _totalSupply; }
16,849,497
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./Controllable.sol"; import "./ITokenSale.sol"; /// tokensale implementation contract TokenSale is ITokenSale, Controllable, Initializable { address private payee; address private soldToken; uint256 private salePrice_; uint256 private issueCount; uint256 private maxCount; uint256 private vipReserve; uint256 private vipIssued; TokenMinting[] private _purchasers; TokenMinting[] private _mintees; address private _partner; uint256 private _permill; bool private _openState; /// @notice Called to purchase some quantity of a token /// @param _soldToken - the erc721 address /// @param _salePrice - the sale price /// @param _maxCount - the max quantity /// @param _vipReserve - the vip reserve to set aside for minting directly constructor(address _soldToken, uint256 _salePrice, uint256 _maxCount, uint256 _vipReserve) { _addController(msg.sender); payee = msg.sender; soldToken = _soldToken; salePrice_ = _salePrice; issueCount = 0; maxCount = _maxCount; vipReserve = _vipReserve; vipIssued = 0; } /// @dev called after constructor once to init stuff function initialize(address partner, uint256 permill) public initializer { require(IMintable(soldToken).getMinter() == address(this), "soldToken must be controllable by this contract"); _partner = partner; _permill = permill; } /// @dev create a token hash using the address of this objcet, sender address and the current issue count function _createTokenHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(address(this), msg.sender, issueCount))); } /// @notice Called to purchase some quantity of a token /// @param receiver - the address of the account receiving the item /// @param quantity - the quantity to purchase. max 5. function purchase(address receiver, uint256 quantity) external payable override returns (TokenMinting[] memory mintings) { require(issueCount + quantity + vipReserve <= maxCount, "cannot purchase more than maxCount"); require(salePrice_ * quantity <= msg.value, "must attach funds to purchase items"); require(quantity > 0 && quantity <= 5, "cannot purchase more than 5 items"); require(_openState, "cannot mint when tokensale is closed"); // mint the desired tokens to the receiver mintings = new TokenMinting[](quantity); for(uint256 i = 0; i < quantity; i++) { TokenMinting memory _minting = TokenMinting(receiver, _createTokenHash()); // create a record of this new minting _purchasers.push(_minting); // and get a refence to it mintings[i] = _minting; issueCount = issueCount + 1; // mint the token IMintable(soldToken).mint(receiver, _minting.tokenHash); // emit an event to that respect emit TokenMinted(receiver, _minting.tokenHash, 0); } uint256 partnerShare = 0; // transfer to partner share if(_partner != address(0) && _permill > 0) { partnerShare = msg.value * _permill / 1000000; payable(_partner).transfer(partnerShare); } uint256 ourShare = msg.value - partnerShare; payable(payee).transfer(ourShare); } /// @notice returns the sale price in ETH for the given quantity. /// @param quantity - the quantity to purchase. max 5. /// @return price - the sale price for the given quantity function salePrice(uint256 quantity) external view override returns (uint256 price) { price = salePrice_ * quantity; } /// @notice Mint a specific tokenhash to a specific address ( up to har-cap limit) /// only for controller of token /// @param receiver - the address of the account receiving the item /// @param tokenHash - token hash to mint to the receiver function mint(address receiver, uint256 tokenHash) external override onlyController { require(vipIssued < vipReserve, "cannot mint more than the reserve"); require(issueCount < maxCount, "cannot mint more than maxCount"); vipIssued = vipIssued + 1; issueCount = issueCount + 1; _mintees.push(TokenMinting(receiver, _createTokenHash())); IMintable(soldToken).mint(receiver, tokenHash); // emit an event to that respect emit TokenMinted(receiver, tokenHash, 1); } /// @notice set the revenue partner on this tokensale. we split revenue with the partner /// only for controller of token /// @param partner - the address of the partner. will receive x%% of the revenue /// @param permill - permilliage of the revenue to be split. min 0 max 1000000 function setRevenuePartner(address partner, uint256 permill) external override onlyController { require(permill >= 0 && permill <= 1000000, "permill must be between 0 and 1000000"); _partner = partner; _permill = permill; emit RevenuePartnerChanged(partner, permill); } /// @notice get the revenue partner on this tokensale. we split revenue with the partner /// @return partner - the address of the partner. will receive x%% of the revenue /// @return permill - permilliage of the revenue to be split. permill = 1 / 1000000 function getRevenuePartner() external view override returns (address partner, uint256 permill) { return (_partner, _permill); } /// @notice open / close the tokensale /// only for controller of token /// @param openState - the open state of the tokensale function setOpenState(bool openState) external override onlyController { _openState = openState; } /// @notice get the token sale open state /// @return openState - the open state of the tokensale function getOpenState() external view override returns (bool openState) { openState = _openState; } /// @notice set the psale price /// only for controller of token /// @param _salePrice - the open state of the tokensale function setSalePrice(uint256 _salePrice) external override onlyController { require(salePrice_ > 0, "salePrice must be greater than 0"); salePrice_ = _salePrice; } /// @notice get the token sale price /// @return salePrice - the open state of the tokensale function getSalePrice() external view override returns (uint256) { return salePrice_; } /// @notice set the psale price /// only for controller of token /// @param _payee - the open state of the tokensale function setPayee(address _payee) external override onlyController { require(_payee != address(0), "payee cannoot be zero address"); payee = _payee; emit PayeeChanged(payee); } /// @notice get the token sale price /// @return salePrice - the open state of the tokensale function getPayee() external view override returns (address) { return payee; } /// @notice get the address of the sole token /// @return token - the address of the sole token function getSaleToken() external view override returns (address token) { return soldToken; } /// @notice get the total list of purchasers /// @return _list - total list of purchasers function purchaserList() external view override returns (TokenMinting[] memory _list) { _list = _purchasers; } /// @notice get the total list of minters /// @return _list - total list of purchasers function minterList() external view override returns (TokenMinting[] memory _list) { _list = _mintees; } }
get the total list of purchasers return _list - total list of purchasers
function purchaserList() external view override returns (TokenMinting[] memory _list) { _list = _purchasers; }
15,835,814
./full_match/1313161554/0x8535bC7a55E090DACc9c201A758CD035672f5e10/sources/contracts/marketplace/Marketplace.sol
Tax txn by transfering fees to Farandole and royalties to the rightsowner if applicable grossSaleValue - the price at which the asset will be sold tokenId - used to fetch the rightsowner and royalties amount return netSaleAmount - the value that will go to the seller after deducting fees and royalties
function _taxTxn(address sender, IERC721 token, uint tokenId, uint grossSaleValue, ERC20 currency) internal virtual returns (uint) { uint paidFees = _payFees(sender, grossSaleValue, currency); (uint paidRoyalties, address receiver) = _payRoyalties(sender, token, tokenId, grossSaleValue, currency); emit RoyaltiesAndFeesPaid(token, tokenId, paidRoyalties, receiver, paidFees, farandoleWallet); return grossSaleValue - (paidRoyalties + paidFees); }
13,233,567
./full_match/80001/0x2A78c15604a0ff4D368d7BE13ade78C5362B6Ce1/sources/project_/contracts/Token.sol
generate the uniswap pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapV2Router.WETH(); _approve(address(this), address(uniSwapV2Router), tokenAmount); uniSwapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
836,475
./full_match/1/0xA694b177C957F3a440e3FDEe8Caefb9C8ae74f52/sources/browser/contract.sol
---------- ADMINISTRATOR ONLY FUNCTIONS ----------/ administrator can manually disable the ambassador phase./
function disableInitialStage() public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "EthPire: must have administrator role"); onlyAmbassadors = false; }
3,049,650
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant 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) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex 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 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @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[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @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. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @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 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/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.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant 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) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex 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 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @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[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @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. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @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 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // 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.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = 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); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool ๐Ÿ™‡ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // 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.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant 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) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex 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 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @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[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @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. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @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( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
A simple method to calculate amount of each underlying tokens that is returned upon burning given amount of LP tokens account the address that is withdrawing tokens amount the amount of LP tokens that would be burned on withdrawal return array of token balances that the user will receive/
function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); }
970,662
./partial_match/1/0xD59BcAbd00721B754aCB79FE668faE4B6A063fF8/sources/contracts/carbon/CarbonController.sol
@inheritdoc ICarbonController/ don't allow unnecessary eth
function createStrategy( Token token0, Token token1, Order[2] calldata orders ) external payable nonReentrant whenNotPaused onlyProxyDelegate returns (uint256) { _validateInputTokens(token0, token1); if (msg.value > 0 && !token0.isNative() && !token1.isNative()) { revert UnnecessaryNativeTokenReceived(); } if (!_pairExists(token0, token1)) { strategyPair = _createPair(token0, token1); strategyPair = _pair(token0, token1); } Token[2] memory tokens = [token0, token1]; return _createStrategy(_voucher, tokens, orders, strategyPair, msg.sender, msg.value); }
2,647,151
./partial_match/1/0x6e1781678ffE6CDc109fd3bC0833c47BD0F23de1/sources/contracts/L1/ValidatorPool.sol
Sends reward message to ValidatorRewardVault contract on L2 using Portal. _output The finalized output./ Pay out rewards via L2 Vault now that the output is finalized.
function _sendRewardMessageToL2Vault(Types.CheckpointOutput memory _output) private { PORTAL.depositTransactionByValidatorPool( Predeploys.VALIDATOR_REWARD_VAULT, VAULT_REWARD_GAS_LIMIT, abi.encodeWithSelector( ValidatorRewardVault.reward.selector, _output.submitter, _output.l2BlockNumber ) ); }
16,157,664
./partial_match/4/0x2F674500a367583D6Aaef312478a7cC1941a1977/sources/FECORE.sol
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); }
8,664,341
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; function ownerOf(uint256 tokenId) external view returns (address); } interface IMoonCatReference { function doc (address contractAddress) external view returns (string memory name, string memory description, string memory details); function setDoc (address contractAddress, string calldata name, string calldata description) external; } interface IMoonCatTraits { function kTraitsOf (bytes5 catId) external view returns (bool genesis, bool pale, uint8 facing, uint8 expression, uint8 pattern, uint8 pose); } interface IMoonCatColors { function colorsOf (bytes5 catId) external view returns (uint8[24] memory); } /** * @title MoonCatSVGs * @notice On Chain MoonCat Image Generation * @dev Builds SVGs of MoonCat Images */ contract MoonCatSVGs { /* External Contracts */ IMoonCatRescue MoonCatRescue = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); IMoonCatReference MoonCatReference; IMoonCatTraits MoonCatTraits; IMoonCatColors MoonCatColors; address MoonCatAcclimatorAddress = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69; uint8[16] public CatBox = [53, 49, 42, 34, 51, 49, 40, 28, 51, 49, 34, 44, 53, 37, 40, 42]; string constant public Face = "57 51,59 51,59 53,61 53,61 55,67 55,67 53,69 53,69 51,71 51,71 53,69 53,69 55,71 55,71 57,73 57,73 67,71 67,71 69,57 69,57 67,55 67,55 57,57 57,57 55,59 55,59 53,57 53"; string[4] public Border = ["57 49,59 49,59 51,61 51,61 53,67 53,67 51,69 51,69 49,71 49,71 51,73 51,73 55,75 55,75 59,85 59,85 61,87 61,87 65,89 65,89 61,87 61,87 55,93 55,93 59,95 59,95 69,93 69,93 71,89 71,89 75,87 75,87 77,85 77,85 79,83 79,83 81,81 81,81 83,61 83,61 77,59 77,59 75,57 75,57 69,55 69,55 67,53 67,53 55,55 55,55 51,57 51", "57 49,59 49,59 51,61 51,61 53,67 53,67 51,69 51,69 49,71 49,71 51,73 51,73 55,83 55,83 57,89 57,89 61,91 61,91 71,89 71,89 73,87 73,87 75,85 75,85 77,69 77,69 75,53 75,53 73,51 73,51 65,53 65,53 55,55 55,55 51,57 51", "57 49,59 49,59 51,61 51,61 53,67 53,67 51,69 51,69 49,73 49,73 55,75 55,75 69,79 69,79 71,83 71,83 75,85 75,85 85,83 85,83 87,81 87,81 89,77 89,77 93,71 93,71 91,65 91,65 93,61 93,61 91,59 91,59 83,57 83,57 77,55 77,55 75,51 75,51 69,55 69,55 67,53 67,53 55,55 55,55 51,57 51", "57 49,61 49,61 53,67 53,67 51,69 51,69 49,73 49,73 53,77 53,77 51,79 51,79 49,83 49,83 45,81 45,81 43,77 43,77 45,73 45,73 37,85 37,85 39,89 39,89 45,91 45,91 51,93 51,93 61,91 61,91 67,93 67,93 73,91 73,91 77,89 77,89 79,81 79,81 77,75 77,75 75,71 75,71 77,69 77,69 79,63 79,63 77,61 77,61 79,53 79,53 73,55 73,55 71,57 71,57 69,55 69,55 67,53 67,53 53,55 53,55 51,57 51"]; string[4] public Coat = ["59 71,71 71,71 69,73 69,73 67,75 67,75 61,83 61,83 63,85 63,85 67,91 67,91 59,89 59,89 57,91 57,91 59,93 59,93 67,91 67,91 69,87 69,87 73,85 73,85 75,83 75,83 77,81 77,81 79,79 79,79 81,77 81,77 75,79 75,79 73,69 73,69 75,71 75,71 79,69 79,69 77,67 77,67 75,65 75,65 79,63 79,63 77,61 77,61 75,59 75", "53 69,57 69,57 71,73 71,73 73,81 73,81 71,83 71,83 69,85 69,85 67,81 67,81 65,79 65,79 67,81 67,81 71,79 71,79 69,73 69,73 67,75 67,75 59,77 59,77 57,81 57,81 59,87 59,87 63,89 63,89 69,87 69,87 71,85 71,85 73,83 73,83 75,71 75,71 71,69 71,69 73,65 73,65 71,59 71,59 73,55 73,55 71,53 71", "55 69,57 69,57 71,71 71,71 69,73 69,73 71,75 71,75 75,77 75,77 85,79 85,79 81,81 81,81 77,79 77,79 73,77 73,77 71,79 71,79 73,81 73,81 77,83 77,83 83,81 83,81 85,79 85,79 87,75 87,75 89,69 89,69 87,67 87,67 85,71 85,71 83,75 83,75 81,69 81,69 85,67 85,67 77,65 77,65 75,67 75,67 73,61 73,61 77,63 77,63 79,61 79,61 89,65 89,65 87,63 87,63 85,61 85,61 81,59 81,59 75,57 75,57 73,55 73", "89 49,85 49,85 43,81 43,81 41,77 41,77 43,75 43,75 39,83 39,83 41,87 41,87 47,89 47,89 53,91 53,91 59,89 59,89 67,91 67,91 71,89 71,89 75,87 75,87 77,85 77,85 75,79 75,79 71,83 71,83 73,81 73,81 75,85 75,85 73,87 73,87 69,85 69,85 63,83 63,83 65,79 65,79 67,77 67,77 71,73 71,73 73,69 73,69 75,65 75,65 73,63 73,63 75,59 75,59 77,57 77,57 57,55 57,55 53,57 53,57 57,71 57,71 53,73 53,73 57,57 57,57 73,59 73,59 71,71 71,71 69,75 69,75 57,77 57,77 55,79 55,79 53,81 53,81 51,89 51"]; string[4] public Tummy = ["71 73,77 73,77 75,75 75,75 79,73 79,73 75,71 75", "75 69,79 69,79 71,75 71", "61 79,67 79,67 87,63 87,63 85,61 85", "83 63,85 63,85 67,83 67,83 69,77 69,77 67,79 67,79 65,83 65"]; uint8[] public Eyes = [2,0,0,0, 59,59,67,59]; uint8[] public Whiskers = [4,4,4,4, 59,63,67,63,61,65,65,65, 59,57,67,57,61,65,65,65, 59,61,67,61,61,65,65,65, 57,63,59,63,67,63,69,63]; uint8[] public Skin = [6,5,7,7, 57,53,69,53,63,63,63,79,69,79,75,79, 57,53,69,53,63,63,59,71,63,71, 57,53,69,53,63,63,53,71,63,75,63,89,73,89, 57,53,69,53,63,63,77,73,55,75,65,75,83,75]; uint8[882] public Patterns = [16,17,17,18,34,25,27,40,62,53,56,70, 61,55,65,55,55,59,71,59,79,61,91,61,55,63,71,63,77,63,83,63,81,65,91,65,87,67,85,69,59,73,69,75, 61,55,65,55,55,59,71,59,79,59,85,59,77,61,83,61,55,63,71,63,87,65,55,69,67,71,83,71,73,73,77,73,81,73, 61,55,65,55,55,59,71,59,55,63,71,63,57,71,73,71,59,73,71,73,79,73,75,75,73,77,81,77,81,81,79,83,61,85, 77,39,81,39,81,41,85,41,85,45,81,53,61,55,65,55,77,55,83,55,79,57,55,59,71,59,55,63,71,63,89,67,59,73,67,73, 69,51,67,53,57,57,59,57,89,57,57,59,91,59,71,61,77,61,79,61,81,61,91,61,71,63,79,63,81,63,83,63,55,65,81,65,73,67,73,69,75,69,61,71,63,71,65,71,71,71,73,71,75,71,79,71,81,71,63,73,79,73,81,73,83,73,81,75, 69,51,67,53,57,57,59,57,57,59,81,59,83,59,85,59,71,61,83,61,85,61,71,63,55,65,77,65,77,67,79,67,53,69,55,69,55,71,57,71,71,71,71,73,73,73,75,73,77,73, 69,51,67,53,57,57,59,57,57,59,71,61,71,63,55,65,57,71,59,71,61,71,63,71,77,71,59,73,79,73,71,75,75,75,79,75,73,77,75,77,73,79,75,79,75,81,75,83,61,85,61,87,63,87, 75,39,77,39,79,39,81,39,75,41,81,41,69,51,81,51,83,51,85,51,67,53,71,53,79,53,81,53,83,53,77,55,79,55,81,55,83,55,57,57,59,57,79,57,81,57,57,59,87,59,71,61,85,61,87,61,71,63,85,63,87,63,55,65,87,65,87,67,89,67,59,71,61,71,63,71,65,71,61,73, 57,51,59,53,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,81,61,55,63,57,63,59,63,61,63,65,63,81,63,83,63,55,65,57,65,59,65,61,65,63,65,65,65,81,65,83,65,57,67,59,67,61,67,63,67,65,67,79,67,81,67,83,67,85,67,87,67,89,67,71,69,73,69,81,69,83,69,67,71,69,71,71,71,73,71,75,71,65,73,67,73,67,75,69,75,69,77,75,79, 57,51,59,53,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,83,61,85,61,55,63,57,63,59,63,61,63,65,63,83,63,85,63,87,63,55,65,57,65,59,65,61,65,63,65,65,65,81,65,83,65,85,65,87,65,57,67,59,67,61,67,63,67,65,67,85,67,87,67,83,69,85,69,63,71,65,71,67,71,83,71, 57,51,59,53,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,55,63,57,63,59,63,61,63,65,63,55,65,57,65,59,65,61,65,63,65,65,65,57,67,59,67,61,67,63,67,65,67,67,73,65,75,67,75,69,75,67,77,69,77,75,81,79,81,81,81,73,83,75,83,79,83,61,85,73,85,75,85,77,85,61,87,63,87,73,87,73,89, 85,43,85,45,85,47,87,47,57,51,81,51,83,51,85,51,87,51,55,53,59,53,83,53,85,53,87,53,55,55,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,55,63,57,63,59,63,61,63,65,63,75,63,77,63,79,63,55,65,57,65,59,65,61,65,63,65,65,65,75,65,77,65,57,67,59,67,61,67,63,67,65,67,75,67,71,69,73,69,75,69,87,69,65,71,67,71,69,71,71,71,87,71,65,73,67,73,85,73,87,73,83,75,85,75]; /** * @dev Wrap a chunk of SVG objects with a group that flips their appearance horizontally. */ function flip (bytes memory svgData) public pure returns (bytes memory) { return abi.encodePacked("<g transform=\"scale(-1,1) translate(-128,0)\">", svgData, "</g>"); } /** * @dev Transform a set of coordinate points into an SVG polygon object. */ function polygon(string memory points, uint8 r, uint8 g, uint8 b) internal pure returns (bytes memory) { return abi.encodePacked("<polygon points=\"", points, "\" fill=\"rgb(",uint2str(r),",",uint2str(g),",",uint2str(b), ")\"/>" ); } /** * @dev Transform a coordinate point into SVG rectangles. */ function setPixel (bytes memory imageData, uint8 x, uint8 y) internal pure returns (bytes memory) { return abi.encodePacked(imageData, "<use href=\"#r", "\" x=\"",uint2str(x), "\" y=\"",uint2str(y), "\"/>"); } /** * @dev Transform a set of coordinate points into a collection of SVG rectangles. */ function pixelGroup (uint8[] memory data, uint8 index) public pure returns (bytes memory) { bytes memory pixels; uint startIndex = 2; for (uint i = 0; i < index; i++) { startIndex += data[i]; } uint endIndex = startIndex + data[index]; for (uint i = startIndex; i < endIndex; i++){ uint p = i * 2; pixels = setPixel(pixels, data[p], data[p+1]); } return pixels; } /** * @dev For a given MoonCat pose and pattern ID, return a collection of SVG rectangles drawing that pattern. */ function getPattern (uint8 pose, uint8 pattern) public view returns (bytes memory) { bytes memory pixels; if (pattern > 0) { pattern -= 1; uint index = (pattern << 2) + pose; uint startIndex = 6; for (uint i = 0; i < index; i++) { startIndex += Patterns[i]; } uint endIndex = startIndex + Patterns[index]; for (uint i = startIndex; i < endIndex; i++){ uint p = i * 2; pixels = setPixel(pixels, Patterns[p], Patterns[p+1]); } } return pixels; } /** * @dev Wrap a collection of SVG rectangle "pixels" in a group to color them all the same color. */ function colorGroup (bytes memory pixels, uint8 r, uint8 g, uint8 b) internal pure returns (bytes memory) { return abi.encodePacked("<g fill=\"rgb(",uint2str(r),",",uint2str(g),",",uint2str(b),")\">", pixels, "</g>"); } /** * @dev Wrap a collection of SVG rectangle "pixels" in a group to create a colored glow around them. */ function glowGroup (bytes memory pixels, uint8 r, uint8 g, uint8 b) public pure returns (bytes memory) { return abi.encodePacked("<g style=\"filter:drop-shadow(0px 0px 2px rgb(",uint2str(r), ",", uint2str(g), ",", uint2str(b),"))\">", pixels, "</g>"); } /** * @dev Given specific MoonCat trait information, assemble the main visual SVG objects to represent a MoonCat with those traits. */ function getPixelData (uint8 facing, uint8 expression, uint8 pose, uint8 pattern, uint8[24] memory colors) public view returns (bytes memory) { bytes memory border = polygon(Border[pose], colors[3], colors[4], colors[5]); bytes memory face = polygon(Face, colors[9], colors[10], colors[11]); bytes memory coat = polygon(Coat[pose], colors[9], colors[10], colors[11]); bytes memory skin = colorGroup(pixelGroup(Skin, pose), colors[15], colors[16], colors[17]); bytes memory tummy = polygon(Tummy[pose], colors[12], colors[13], colors[14]); bytes memory patt = colorGroup(getPattern(pose, pattern), colors[6], colors[7], colors[8]); bytes memory whiskers = colorGroup(pixelGroup(Whiskers, expression), colors[12], colors[13], colors[14]); bytes memory eyes = colorGroup(pixelGroup(Eyes, 0), colors[3], colors[4], colors[5]); bytes memory data; if (pattern == 2) { data = abi.encodePacked(border, face, coat, skin, tummy, whiskers, patt, eyes); } else { data = abi.encodePacked(border, face, coat, skin, tummy, patt, whiskers, eyes); } if (facing == 1) { return flip(data); } return data; } /** * @dev Construct SVG header/wrapper tag for a given set of canvas dimensions. */ function svgTag (uint8 x, uint8 y, uint8 w, uint8 h) public pure returns (bytes memory) { return abi.encodePacked("<svg xmlns=\"http://www.w3.org/2000/svg\" preserveAspectRatio=\"xMidYMid slice\" viewBox=\"", uint2str(x), " ", uint2str(y), " ", uint2str(w), " ", uint2str(h), "\" width=\"", uint2str(uint32(w)*5), "\" height=\"", uint2str(uint32(h)*5), "\" shape-rendering=\"crispEdges\" style=\"image-rendering:pixelated\"><defs><rect id=\"r\" width=\"2\" height=\"2\" /></defs>"); } /** * @dev Convert a MoonCat facing and pose trait information into an SVG viewBox definition to set that canvas size. */ function boundingBox (uint8 facing, uint8 pose) public view returns (uint8 x, uint8 y, uint8 width, uint8 height) { x = CatBox[pose * 4 + 0] - 2; y = CatBox[pose * 4 + 1] - 2; width = CatBox[pose * 4 + 2] + 4; height = CatBox[pose * 4 + 3] + 4; if (facing == 1) { x = 128 - width - x; } return (x, y, width, height); } /** * @dev For a given MoonCat hex ID, create an SVG of their appearance, specifying glowing or not. */ function imageOf (bytes5 catId, bool glow) public view returns (string memory) { (,,uint8 facing, uint8 expression, uint8 pattern, uint8 pose) = MoonCatTraits.kTraitsOf(catId); uint8[24] memory colors = MoonCatColors.colorsOf(catId); bytes memory pixelData = getPixelData(facing, expression, pose, pattern, colors); if (glow) { pixelData = glowGroup(pixelData, colors[0], colors[1], colors[2]); } (uint8 x, uint8 y, uint8 width, uint8 height) = boundingBox(facing, pose); return string(abi.encodePacked(svgTag(x, y, width, height), pixelData, "</svg>")); } /** * @dev For a given MoonCat hex ID, create an SVG of their appearance, glowing if they're Acclimated. */ function imageOf (bytes5 catId) public view returns (string memory) { return imageOf(catId, MoonCatRescue.catOwners(catId) == MoonCatAcclimatorAddress); } /** * @dev For a given MoonCat rescue order, create an SVG of their appearance, specifying glowing or not. */ function imageOf (uint256 rescueOrder, bool glow) public view returns (string memory) { require(rescueOrder < 25440, "Invalid Rescue Order"); return imageOf(MoonCatRescue.rescueOrder(rescueOrder), glow); } /** * @dev For a given MoonCat rescue order, create an SVG of their appearance, glowing if they're Acclimated. */ function imageOf (uint256 rescueOrder) public view returns (string memory) { require(rescueOrder < 25440, "Invalid Rescue Order"); return imageOf(MoonCatRescue.rescueOrder(rescueOrder)); } /** * @dev Convert an integer/numeric value into a string of that number's decimal value. */ function uint2str (uint value) public pure returns (string memory) { 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); } /* General */ /** * @dev Get documentation about this contract. */ function doc() public view returns (string memory name, string memory description, string memory details) { return MoonCatReference.doc(address(this)); } constructor (address MoonCatReferenceAddress, address MoonCatTraitsAddress, address MoonCatColorsAddress) { owner = payable(msg.sender); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender); MoonCatReference = IMoonCatReference(MoonCatReferenceAddress); MoonCatTraits = IMoonCatTraits(MoonCatTraitsAddress); MoonCatColors = IMoonCatColors(MoonCatColorsAddress); } address payable public owner; modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } /** * @dev Allow current `owner` to transfer ownership to another address. */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Update the location of the Reference Contract. */ function setReferenceContract (address referenceContract) public onlyOwner { MoonCatReference = IMoonCatReference(referenceContract); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20 (address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721 (address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } }
Convert an integer/numeric value into a string of that number's decimal value./
function uint2str (uint value) public pure returns (string memory) { 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); }
394,128
pragma solidity 0.4.23; /** * @title Utility interfaces * @author Biglabs Pte. Ltd. * @dev Smart contract with owner */ contract Owner { /** * @dev Get smart contract's owner * @return The owner of the smart contract */ function owner() public view returns (address); //check address is a valid owner (owner or coOwner) function isValidOwner(address _address) public view returns(bool); } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Utility smart contracts * @author Biglabs Pte. Ltd. * @dev Upgradable contract with agent */ contract Upgradable { function upgrade() public; function getRequiredTokens(uint _level) public pure returns (uint); function getLevel() public view returns (uint); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Utility smart contracts * @author Biglabs Pte. Ltd. * @dev Timeline smart contract (within the period) */ contract Timeline { //start time uint public startTime; //end time uint public endTime; modifier started() { require(now >= startTime); _; } modifier notEnded() { require(now <= endTime); _; } modifier isEnded() { require(now >= endTime); _; } modifier onlyWhileOpen() { require(now >= startTime && now <= endTime); _; } /** * @dev Timeline constructor * @param _startTime The opening time in seconds (unix Time) * @param _endTime The closing time in seconds (unix Time) */ function Timeline( uint256 _startTime, uint256 _endTime ) public { require(_startTime > now); require(_endTime > _startTime); startTime = _startTime; endTime = _endTime; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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 balance) { return balances[_owner]; } } /** * @title Utility interfaces * @author Biglabs Pte. Ltd. * @dev ERC20 smart contract with owner */ contract OwnerERC20 is ERC20Basic, Owner { } /** * @title Utility smart contracts * @author Biglabs Pte. Ltd. * @dev Chain smart contract with the same owner */ contract ChainOwner is Owner { //parent contract OwnerERC20 internal parent; /** * @param _parent The parent smart contract */ function ChainOwner(OwnerERC20 _parent) internal { parent = _parent; } modifier onlyOwner() { require(parent.isValidOwner(msg.sender)); _; } function owner() public view returns (address) { return parent.owner(); } modifier validOwner(OwnerERC20 _smzoToken) { //check if function not called by owner or coOwner if (!parent.isValidOwner(msg.sender)) { //require this called from smart contract OwnerERC20 ico = OwnerERC20(msg.sender); //this will throw exception if not //ensure the same owner require(ico.owner() == _smzoToken.owner()); } _; } function isValidOwner(address _address) public view returns(bool) { if (_address == owner()) { return true; } return false; } } /** * @title Utility smart contracts * @author Biglabs Pte. Ltd. * @dev Chain smart contract with the same owner */ contract ChainCoOwner is ChainOwner { mapping(address=>bool) internal coOwner; address[] internal coOwnerList; /** * @param _parent The parent smart contract * @param _coOwner Array of coOwner */ function ChainCoOwner(OwnerERC20 _parent, address[] _coOwner) ChainOwner(_parent) internal { _addCoOwners(_coOwner); } function _addCoOwners(address[] _coOwner) internal { uint len = _coOwner.length; for (uint i=0; i < len; i++) { coOwner[_coOwner[i]] = true; coOwnerList.push(_coOwner[i]); } } function _addCoOwner(address _coOwner) internal { coOwner[_coOwner] = true; coOwnerList.push(_coOwner); } function _disableCoOwners(address[] _coOwner) internal { uint len = _coOwner.length; for (uint i=0; i < len; i++) { coOwner[_coOwner[i]] = false; } } function _disableCoOwner(address _coOwner) internal { coOwner[_coOwner] = false; } /** * @dev Check address is valid owner (owner or coOwner) * @param _address Address to check * */ function isValidOwner(address _address) public view returns(bool) { if (_address == owner() || coOwner[_address] == true) { return true; } return false; } } /** * @title Utility interfaces * @author Biglabs Pte. Ltd. * @dev ICO smart contract */ contract ICO is OwnerERC20 { //transfer tokens (use wei contribution information) function transferByEth(address _to, uint _weiAmount, uint _value) public returns (bool); //calculate no tokens function calculateNoToken(uint _weiAmount) public view returns(uint); } /** * @title Mozo sale token for ICO * @author Biglabs Pte. Ltd. */ contract MozoSaleToken is BasicToken, Timeline, ChainCoOwner, ICO { using SafeMath for uint; //sale token name, use in ICO phase only string public constant name = "Mozo Sale Token"; //sale token symbol, use in ICO phase only string public constant symbol = "SMZO"; //token symbol uint8 public constant decimals = 2; //KYC/AML threshold: 20k SGD = 15k USD = 165k token (x100) uint public constant AML_THRESHOLD = 16500000; //No. repicients that has bonus tokens uint public noBonusTokenRecipients; //total no. bonus tokens uint public totalBonusToken; //bonus transferred flags mapping(address => bool) bonus_transferred_repicients; //maximum transferring per function uint public constant MAX_TRANSFER = 80; //number of transferred address uint public transferredIndex; //indicate hardcap is reached or not bool public isCapped = false; //total wei collected uint public totalCapInWei; //rate uint public rate; //flag indicate whether ICO is stopped for bonus bool public isStopped; //hold all address to transfer Mozo tokens when releasing address[] public transferAddresses; //whitelist (Already register KYC/AML) mapping(address => bool) public whitelist; //contain map of address that buy over the threshold for KYC/AML //but buyer is not in the whitelist yes mapping(address => uint) public pendingAmounts; /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev Only owner or coOwner */ modifier onlyOwnerOrCoOwner() { require(isValidOwner(msg.sender)); _; } /** * @dev Only stopping for bonus distribution */ modifier onlyStopping() { require(isStopped == true); _; } /** * Only owner or smart contract of the same owner in chain. */ modifier onlySameChain() { //check if function not called by owner or coOwner if (!isValidOwner(msg.sender)) { //require this called from smart contract ChainOwner sm = ChainOwner(msg.sender); //this will throw exception if not //ensure the same owner require(sm.owner() == owner()); } _; } /** * @notice owner should transfer to this smart contract {_supply} Mozo tokens manually * @param _mozoToken Mozo token smart contract * @param _coOwner Array of coOwner * @param _supply Total number of tokens = No. tokens * 10^decimals = No. tokens * 100 * @param _rate number of wei to buy 0.01 Mozo sale token * @param _openingTime The opening time in seconds (unix Time) * @param _closingTime The closing time in seconds (unix Time) */ function MozoSaleToken( OwnerERC20 _mozoToken, address[] _coOwner, uint _supply, uint _rate, uint _openingTime, uint _closingTime ) public ChainCoOwner(_mozoToken, _coOwner) Timeline(_openingTime, _closingTime) onlyOwner() { require(_supply > 0); require(_rate > 0); rate = _rate; totalSupply_ = _supply; //assign all sale tokens to owner balances[_mozoToken.owner()] = totalSupply_; //add owner and co_owner to whitelist addAddressToWhitelist(msg.sender); addAddressesToWhitelist(_coOwner); emit Transfer(0x0, _mozoToken.owner(), totalSupply_); } function addCoOwners(address[] _coOwner) public onlyOwner { _addCoOwners(_coOwner); } function addCoOwner(address _coOwner) public onlyOwner { _addCoOwner(_coOwner); } function disableCoOwners(address[] _coOwner) public onlyOwner { _disableCoOwners(_coOwner); } function disableCoOwner(address _coOwner) public onlyOwner { _disableCoOwner(_coOwner); } /** * @dev Get Rate: number of wei to buy 0.01 Mozo token */ function getRate() public view returns (uint) { return rate; } /** * @dev Set Rate: * @param _rate Number of wei to buy 0.01 Mozo token */ function setRate(uint _rate) public onlyOwnerOrCoOwner { rate = _rate; } /** * @dev Get flag indicates ICO reached hardcap */ function isReachCapped() public view returns (bool) { return isCapped; } /** * @dev add an address to the whitelist, sender must have enough tokens * @param _address address for adding to whitelist * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _address) onlyOwnerOrCoOwner public returns (bool success) { if (!whitelist[_address]) { whitelist[_address] = true; //transfer pending amount of tokens to user uint noOfTokens = pendingAmounts[_address]; if (noOfTokens > 0) { pendingAmounts[_address] = 0; transfer(_address, noOfTokens); } success = true; } } /** * @dev add addresses to the whitelist, sender must have enough tokens * @param _addresses addresses for adding to whitelist * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _addresses) onlyOwnerOrCoOwner public returns (bool success) { uint length = _addresses.length; for (uint i = 0; i < length; i++) { if (addAddressToWhitelist(_addresses[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param _address address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _address) onlyOwnerOrCoOwner public returns (bool success) { if (whitelist[_address]) { whitelist[_address] = false; success = true; } } /** * @dev remove addresses from the whitelist * @param _addresses addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _addresses) onlyOwnerOrCoOwner public returns (bool success) { uint length = _addresses.length; for (uint i = 0; i < length; i++) { if (removeAddressFromWhitelist(_addresses[i])) { success = true; } } } /** * Stop selling for bonus transfer * @notice Owner should release InvestmentDiscount smart contract before call this */ function setStop() onlyOwnerOrCoOwner { isStopped = true; } /** * @dev Set hardcap is reached * @notice Owner must release all sale smart contracts */ function setReachCapped() public onlyOwnerOrCoOwner { isCapped = true; } /** * @dev Get total distribution in Wei */ function getCapInWei() public view returns (uint) { return totalCapInWei; } /** * @dev Get no. investors */ function getNoInvestor() public view returns (uint) { return transferAddresses.length; } /** * @dev Get unsold tokens */ function getUnsoldToken() public view returns (uint) { uint unsold = balances[owner()]; for (uint j = 0; j < coOwnerList.length; j++) { unsold = unsold.add(balances[coOwnerList[j]]); } return unsold; } /** * @dev Get distributed tokens */ function getDistributedToken() public view returns (uint) { return totalSupply_.sub(getUnsoldToken()); } /** * @dev Override transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public returns (bool) { //required this contract has enough Mozo tokens //obsolete //if (msg.sender == owner()) { // require(parent.balanceOf(this) >= getDistributedToken().add(_value)); //} //we will check it when releasing smart contract //owners or balances already greater than 0, no need to add to list bool notAddToList = isValidOwner(_to) || (balances[_to] > 0); //check AML threshold if (!isStopped) { if (!whitelist[_to]) { if ((_value + balances[_to]) > AML_THRESHOLD) { pendingAmounts[_to] = pendingAmounts[_to].add(_value); return true; } } } if (BasicToken.transfer(_to, _value)) { if (!notAddToList) { transferAddresses.push(_to); } return true; } return false; } /** * @param _weiAmount Contribution in wei * */ function calculateNoToken(uint _weiAmount) public view returns (uint) { return _weiAmount.div(rate); } /** * @dev Override transfer token for a specified address * @param _to The address to transfer to. * @param _weiAmount The wei amount spent to by token */ function transferByEth(address _to, uint _weiAmount, uint _value) public onlyWhileOpen onlySameChain() returns (bool) { if (transfer(_to, _value)) { totalCapInWei = totalCapInWei.add(_weiAmount); return true; } return false; } /** * @dev Release smart contract * @notice Owner must release all sale smart contracts */ function release() public onlyOwnerOrCoOwner { _release(); } /** * @dev Investor claim tokens */ function claim() public isEnded { require(balances[msg.sender] > 0); uint investorBalance = balances[msg.sender]; balances[msg.sender] = 0; parent.transfer(msg.sender, investorBalance); } /** * @param _recipients list of repicients * @param _amount list of no. tokens */ function bonusToken(address[] _recipients, uint[] _amount) public onlyOwnerOrCoOwner onlyStopping { uint len = _recipients.length; uint len1 = _amount.length; require(len == len1); require(len <= MAX_TRANSFER); uint i; uint total = 0; for (i = 0; i < len; i++) { if (bonus_transferred_repicients[_recipients[i]] == false) { bonus_transferred_repicients[_recipients[i]] = transfer(_recipients[i], _amount[i]); total = total.add(_amount[i]); } } totalBonusToken = totalBonusToken.add(total); noBonusTokenRecipients = noBonusTokenRecipients.add(len); } function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } /** * @notice Only call after releasing all sale smart contracts, this smart contract must have enough Mozo tokens * @dev Release smart contract */ function _release() internal { uint length = min(transferAddresses.length, transferredIndex + MAX_TRANSFER); uint i = transferredIndex; if (isCapped) { //Reach hardcap, burn all owner sale token for (; i < length; i++) { address ad = transferAddresses[i]; uint b = balances[ad]; if (b == 0) { continue; } balances[ad] = 0; // send Mozo token from ICO account to investor address parent.transfer(ad, b); } } else { uint unsold = getUnsoldToken(); uint sold = totalSupply_.sub(unsold); if (sold <= 0) { //very bad if we reach here return; } for (; i < length; i++) { ad = transferAddresses[i]; //obsolete //no need to check because we checked before adding //if (ad == owner()) { // continue; //} b = balances[ad]; if (b == 0) { continue; } //distribute all unsold token to investors b = b.add(b.mul(unsold).div(sold)); // send Mozo token from ICO account to investor address balances[ad] = 0; parent.transfer(ad, b); } } transferredIndex = i - 1; //transfer remain tokens to owner //for testing only //parent.transfer(owner(), parent.balanceOf(address(this))); } }
Get Rate: number of wei to buy 0.01 Mozo token/
function getRate() public view returns (uint) { return rate; }
1,016,458
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Faucet { mapping(address => uint256) private _withdrawBlockNumber; function withdraw(uint256 amount) external { _withdrawTo(msg.sender, amount); } function withdrawTo(address to, uint256 amount) external { _withdrawTo(to, amount); } function _withdrawTo(address to, uint256 amount) internal { // Check require( amount <= 1 ether && (_withdrawBlockNumber[to] == 0 || block.number < _withdrawBlockNumber[to] + 10), "TOO_GREEDY" ); // Effect _withdrawBlockNumber[to] = block.number; // Interaction (bool success, ) = to.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls require(success, "CALL_FAILURE"); } receive() external payable {} // solhint-disable-line no-empty-blocks }
Check Effect Interaction
function _withdrawTo(address to, uint256 amount) internal { require( amount <= 1 ether && (_withdrawBlockNumber[to] == 0 || block.number < _withdrawBlockNumber[to] + 10), "TOO_GREEDY" ); _withdrawBlockNumber[to] = block.number; require(success, "CALL_FAILURE"); }
5,344,020
/** *Submitted for verification at Etherscan.io on 2021-03-24 */ // 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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <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 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"); } } } // File: @openzeppelin/contracts/utils/Context.sol 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; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <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 () 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; } } // File: contracts/MoraVesting.sol pragma solidity >=0.6.0 <0.8.0; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a */ contract MoraVesting { using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint private _month = 2629743; //2629743 uint256 private _cliffDuration = _month * 6; uint private _releaseDuration = _month * 5; uint256 private _cliff; uint256 private _start; IERC20 private _token; uint256 private _lastRelease; mapping (address => uint256) private _released; constructor (address token, address beneficiary, uint256 start) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(_cliffDuration + _releaseDuration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(_cliffDuration + _releaseDuration) > block.timestamp, "TokenVesting: final time is before current time"); _token = IERC20(token); _beneficiary = beneficiary; _cliff = start.add(_cliffDuration); _start = start; _lastRelease = _cliff; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _cliff + _releaseDuration; } /** * @return the amount of the token released. */ function released() public view returns (uint256) { return _released[address(_token)]; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { uint256 unreleased = _releasableAmount(); require(block.timestamp < _cliff,"Still-in-cliff"); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(_token)] = _released[address(_token)].add(unreleased); _lastRelease = block.timestamp; _token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(_token), unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function _releasableAmount() private view returns (uint256) { if (block.timestamp - _lastRelease >= _month) { return _vestedAmount().sub(_released[address(_token)]); } return 0; } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount() private view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(_token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_cliffDuration + _releaseDuration+_month)) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_cliff)).div(_releaseDuration); } } }
return the duration of the token vesting./
function duration() public view returns (uint256) { return _cliff + _releaseDuration; }
7,791,672
./partial_match/42/0x2097364Ba2ec75bcE70Ef498B476Bb40A167057F/sources/assignmentToken.sol
TODO: transfer mintership to newminter NOTE: only incumbent minter can transfer mintership NOTE: should emit `MintershipTransfer` event
function transferMintership(address newMinter) public returns (bool) { require(newMinter != address(0)); require(msg.sender == minter); emit MintershipTransfer(minter,newMinter); minter = newMinter; return true; }
8,870,737
// SPDX-License-Identifier: MIT /* โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ•šโ•โ• โ–ˆโ–ˆโ•‘ โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ• */ pragma solidity 0.6.12; import "../../common/Context.sol"; import "../../erc20/IERC20.sol"; import "../../erc20/ERC20Custom.sol"; import "../../erc20/ERC20.sol"; import "../../utils/Owned.sol"; import "../../math/SafeMath.sol"; import "../../gr/Gr.sol"; import "../pool/Pool.sol"; import "../../oracle/UniswapPairOracle.sol"; import "./oracle/ChainlinkBNBPAXGPriceConsumer.sol"; import "../../governance/AccessControl.sol"; contract XauStablecoin is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { Xau, Gr } // BNB and anchor price predictor, one BNB= how much anchor ChainlinkBNBPAXGPriceConsumer private bnb_anchor_pricer; UniswapPairOracle private xauBnbOracle; // Chainlink conversion, Xau-USD, BNB-USD. UniswapPairOracle private grBnbOracle; string public symbol; string public name; uint8 public constant decimals = 18; 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 gr_address; address public xau_bnb_oracle_address; address public gr_bnb_oracle_address; address public wbnb_address; address public bnb_anchor_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M Xau (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 xau address[] public synth_pools_array; // Mapping is also used for faster verification mapping(address => bool) public synth_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 synth_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 Xau 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(synth_pools[msg.sender] == true, "Only xau pools can call this function"); _; } modifier onlyByOwnerGovernanceOrController() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == controller_address, "Not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner || msg.sender == timelock_address || synth_pools[msg.sender] == true, "Not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require(_timelock_address != address(0), "Zero address detected"); name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); synth_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Xau 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 = 'Xau' or 'Gr' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the BNB / Anchor price first, and cut it down to 1e6 precision uint256 _bnb_anchor_price = uint256(bnb_anchor_pricer.consult(wbnb_address, PRICE_PRECISION)); uint256 price_vs_bnb = 0; if (choice == PriceChoice.Xau) { price_vs_bnb = uint256(xauBnbOracle.consult(wbnb_address, PRICE_PRECISION)); // How much Xau if you put in PRICE_PRECISION WBNB } else if (choice == PriceChoice.Gr) { price_vs_bnb = uint256(grBnbOracle.consult(wbnb_address, PRICE_PRECISION)); // How much Gr if you put in PRICE_PRECISION WBNB } else revert("INVALID PRICE CHOICE. Needs to be either 0 (Xau) or 1 (Gr)"); // Will be in 1e6 format return _bnb_anchor_price.mul(PRICE_PRECISION).div(price_vs_bnb); } // Returns 1 Xau = X Anchor function xau_price() public view returns (uint256) { return oracle_price(PriceChoice.Xau); } // Returns 1 Xau = X Anchor function synth_price() public view returns (uint256) { return oracle_price(PriceChoice.Xau); } // Returns 1 Gr = X Anchor function gr_price() public view returns (uint256) { return oracle_price(PriceChoice.Gr); } function bnb_anchor_price() public view returns (uint256) { return uint256(bnb_anchor_pricer.consult(wbnb_address, PRICE_PRECISION)); } // 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 synth_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.Xau), // xau_price() oracle_price(PriceChoice.Gr), // gr_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(bnb_anchor_pricer.consult(wbnb_address, PRICE_PRECISION)) //bnb_anchor_price ); } // Iterate through all xau 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 < synth_pools_array.length; i++){ // Exclude null addresses if (synth_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(Pool(synth_pools_array[i]).collatAnchorBalance()); } } 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 xau_price_cur = xau_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 setXauStep()) if (xau_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= synth_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(synth_step); } } else if (xau_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(synth_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(synth_step); } } last_call_time = block.timestamp; // Set the time of the last expansion emit CollateralRatioRefreshed(global_collateral_ratio); } /* ========== 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 XauBurned(b_address, msg.sender, b_amount); } // This function is what other xau pools will call to mint new Xau function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit XauMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerGovernanceOrController { require(pool_address != address(0), "Zero address detected"); require(synth_pools[pool_address] == false, "Address already exists"); synth_pools[pool_address] = true; synth_pools_array.push(pool_address); emit PoolAdded(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerGovernanceOrController { require(pool_address != address(0), "Zero address detected"); require(synth_pools[pool_address] == true, "Address nonexistant"); // Delete from the mapping delete synth_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < synth_pools_array.length; i++){ if (synth_pools_array[i] == pool_address) { synth_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit PoolRemoved(pool_address); } function setRedemptionFee(uint256 red_fee) public onlyByOwnerGovernanceOrController { redemption_fee = red_fee; emit RedemptionFeeSet(red_fee); } function setMintingFee(uint256 min_fee) public onlyByOwnerGovernanceOrController { minting_fee = min_fee; emit MintingFeeSet(min_fee); } function setSynthStep(uint256 _new_step) public onlyByOwnerGovernanceOrController { synth_step = _new_step; emit SynthStepSet(_new_step); } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerGovernanceOrController { price_target = _new_price_target; emit PriceTargetSet(_new_price_target); } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerGovernanceOrController { refresh_cooldown = _new_cooldown; emit RefreshCooldownSet(_new_cooldown); } function setGrAddress(address _gr_address) public onlyByOwnerGovernanceOrController { require(_gr_address != address(0), "Zero address detected"); gr_address = _gr_address; emit GrAddressSet(_gr_address); } function setBNBAnchorOracle(address _bnb_anchor_consumer_address) public onlyByOwnerGovernanceOrController { require(_bnb_anchor_consumer_address != address(0), "Zero address detected"); bnb_anchor_consumer_address = _bnb_anchor_consumer_address; bnb_anchor_pricer = ChainlinkBNBPAXGPriceConsumer(bnb_anchor_consumer_address); emit BNBAnchorOracleSet(_bnb_anchor_consumer_address); } function setTimelock(address new_timelock) external onlyByOwnerGovernanceOrController { require(new_timelock != address(0), "Zero address detected"); timelock_address = new_timelock; emit TimelockSet(new_timelock); } function setController(address _controller_address) external onlyByOwnerGovernanceOrController { require(_controller_address != address(0), "Zero address detected"); controller_address = _controller_address; emit ControllerSet(_controller_address); } function setPriceBand(uint256 _price_band) external onlyByOwnerGovernanceOrController { price_band = _price_band; emit PriceBandSet(_price_band); } // Sets the Xau_BNB Uniswap oracle address function setSynthBnbOracle(address _xau_oracle_addr, address _wbnb_address) public onlyByOwnerGovernanceOrController { require((_xau_oracle_addr != address(0)) && (_wbnb_address != address(0)), "Zero address detected"); xau_bnb_oracle_address = _xau_oracle_addr; xauBnbOracle = UniswapPairOracle(_xau_oracle_addr); wbnb_address = _wbnb_address; emit XauBNBOracleSet(_xau_oracle_addr, _wbnb_address); } // Sets the Gr_BNB Uniswap oracle address function setGrBnbOracle(address _gr_oracle_addr, address _wbnb_address) public onlyByOwnerGovernanceOrController { require((_gr_oracle_addr != address(0)) && (_wbnb_address != address(0)), "Zero address detected"); gr_bnb_oracle_address = _gr_oracle_addr; grBnbOracle = UniswapPairOracle(_gr_oracle_addr); wbnb_address = _wbnb_address; emit GrBnbOracleSet(_gr_oracle_addr, _wbnb_address); } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; emit CollateralRatioToggled(collateral_ratio_paused); } /* ========== EVENTS ========== */ // Track Xau burned event XauBurned(address indexed from, address indexed to, uint256 amount); // Track Xau minted event XauMinted(address indexed from, address indexed to, uint256 amount); event CollateralRatioRefreshed(uint256 global_collateral_ratio); event PoolAdded(address pool_address); event PoolRemoved(address pool_address); event RedemptionFeeSet(uint256 red_fee); event MintingFeeSet(uint256 min_fee); event SynthStepSet(uint256 new_step); event PriceTargetSet(uint256 new_price_target); event RefreshCooldownSet(uint256 new_cooldown); event GrAddressSet(address _gr_address); event BNBAnchorOracleSet(address bnb_anchor_consumer_address); event TimelockSet(address new_timelock); event ControllerSet(address controller_address); event PriceBandSet(uint256 price_band); event XauBNBOracleSet(address xau_oracle_addr, address wbnb_address); event GrBnbOracleSet(address gr_oracle_addr, address wbnb_address); event CollateralRatioToggled(bool collateral_ratio_paused); }
Sets the Xau_BNB Uniswap oracle address
function setSynthBnbOracle(address _xau_oracle_addr, address _wbnb_address) public onlyByOwnerGovernanceOrController { require((_xau_oracle_addr != address(0)) && (_wbnb_address != address(0)), "Zero address detected"); xau_bnb_oracle_address = _xau_oracle_addr; xauBnbOracle = UniswapPairOracle(_xau_oracle_addr); wbnb_address = _wbnb_address; emit XauBNBOracleSet(_xau_oracle_addr, _wbnb_address); }
952,498
./partial_match/1/0x67c5F13c56aEb40fd9a937214E5429dAf8A0CfC9/sources/contracts/Oracle.sol
Updates the pricing data for a given round _roundData is the data to be updated/
function updateRoundData(uint80 roundId, RoundData calldata _roundData) public onlyTraderAdmin { oracleData[roundId] = _roundData; }
15,753,090